Javascript 查找所有标题标记并检查每个标记是否具有id属性,如果没有,则使用jquery添加id属性
要从内容中查找所有标题标记并检查每个标记是否具有id属性,如果没有,则使用jquery添加id属性Javascript 查找所有标题标记并检查每个标记是否具有id属性,如果没有,则使用jquery添加id属性,javascript,jquery,Javascript,Jquery,要从内容中查找所有标题标记并检查每个标记是否具有id属性,如果没有,则使用jquery添加id属性 下面是我的代码: var headings = $("#edited_content").find("h1,h2,h3,h4,h5,h6"); $.each(headings, function (i, heading) { attributes = heading.attributes $.each(attributes, function (j, val
下面是我的代码:
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);
}
});
});
尝试一个简单的方法
var headings = $("#edited_content").find("h1,h2,h3,h4,h5,h6");
headings.attr('id', function(i, id){
return id || 'prefix-' + i
})
演示:
如果需要,您可以使用not()筛选器(如headers.not('[id]')).attr(…)
尝试以下操作:
if ($(this).attr("id"))) {
alert("id present");
} else {
alert("id absent");
$(this).attr('id', i);
}
在大多数浏览器中,使用数字作为id并不十分有效。@gdoron在html5中是有效的。。。。但是在css中它不起作用。。。。我曾写道,“大多数浏览器”与HTML5都不兼容。