Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/393.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 查找所有标题标记并检查每个标记是否具有id属性,如果没有,则使用jquery添加id属性_Javascript_Jquery - Fatal编程技术网

Javascript 查找所有标题标记并检查每个标记是否具有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

要从内容中查找所有标题标记并检查每个标记是否具有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, 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都不兼容。