H3的内容作为H3的ID

时间:2012-07-23 13:24:29

标签: jquery html

我需要获取<h3></h3>的内容然后小写内容并删除空格(用 - 或_替换它们)然后将它们注入<h3>的ID。

所以,例如......

<li class="widget-first-list"><h3>About This Stuff</h3></li>
<li class="widget-first-list"><h3 id="about-this-stuff">About This Stuff</h3>

这应该存在于页面上的h3s加载中,因此它需要在某处包含'$ this'。

希望这是有道理的 - 我对jQuery没问题,但这给我带来了一些问题。

2 个答案:

答案 0 :(得分:8)

由于您指定了jQuery,所以请转到:

$("h3").each(function() {
    var me = $(this);
    me.attr("id",me.text().toLowerCase().replace(/[^a-z0-9-]/g,'-').replace(/--+/g,'-'));
});

这会将所有非字母数字字符替换为-,然后删除多个连续的-个字符。

在普通JS中(效率更高):

(function() {
    var tags = document.getElementsByTagName("h3"), l = tags.length, i;
    for( i=0; i<l; i++) {
        tags[i].id = tags[i].firstChild.nodeValue.toLowerCase().replace(/[^a-z0-9-]/g,'-').replace(/--+/g,'-');
    }
})();

更好的是,检查重复项:

(function() {
    var tags = document.getElementsByTagName("h3"), l = tags.length, i, newid, n;
    for( i=0; i<l; i++) {
        newid = tags[i].firstChild.nodeValue.toLowerCase().replace(/[^a-z0-9-]/g,'-').replace(/--+/g,'-');
        if( document.getElementById(newid)) {
            n = 1;
            do {n++;}
            while(document.getElementById(newid+'-'+n));
            newid += '-'+n;
        }
        tags[i].id = newid;
    }
})();

答案 1 :(得分:1)

解决方案:

$("h3").each(function() {

    var content = $(this).html().replace(/ /g,'_').toLowerCase();
    $(this).attr("id",content);

});