简体   繁体   English

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

[英]find all header tags and check each tag has id attribute and if not add id attribute using jquery

Want to find all header tags from the content and check each tag has id attribute and if not, then add id attribute using jquery 想要从内容中查找所有标头标签并检查每个标签是否具有id属性,如果没有,则使用jquery添加id属性

Below is my code: 以下是我的代码:

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);
            }
        });
    });

Try a simple 试试一个简单的

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

Demo: Fiddle 演示: 小提琴

If you want you can fine tune it using a not() filter like headings.not('[id]').attr(...) 如果你想要你可以使用像headings.not('[id]').attr(...)那样的not()过滤器来微调它headings.not('[id]').attr(...)

try this: 尝试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM