2014-03-04 39 views
0

想要查找内容中的所有标题标签,并检查每个标签有id属性,如果没有,然后添加id属性使用jquery

找到所有标题标签,并检查每个标签有id属性,如果没有添加id属性使用jquery

下面是我的代码:

var headings = $("#edited_content").find("h1,h2,h3,h4,h5,h6"); 
    $.each(headings, function (i, heading) { 
     attributes = heading.attributes 
     $.each(attributes, function (j, value) { 
      if (value.name == 'id') { 
       alert("id present"); 
      } else { 
       alert("id absent"); 
       $(this).attr('id', i); 
      } 
     }); 
    }); 

回答

2

尝试一个简单的

var headings = $("#edited_content").find("h1,h2,h3,h4,h5,h6"); 
headings.attr('id', function(i, id){ 
    return id || 'prefix-' + i 
}) 

演示:Fiddle

如果你愿意,你可以使用未()过滤微调像headings.not('[id]').attr(...)

+0

使用的编号为ID是不是在大多数浏览器相当有效。 – gdoron

+0

@gdoron在html5中是有效的....但在CSS中它不会工作....任何方式,我们可以很容易地添加一个前缀到编号 –

+0

非常感谢。它的工作是我期望的。 – user2138489

0

试试这个:

if ($(this).attr("id"))) { 
     alert("id present"); 
    } else { 
     alert("id absent"); 
     $(this).attr('id', i); 
    } 
相关问题