H3的内容作为H3的ID

Joh*_*ter 2 html jquery

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

所以,例如......

<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>
Run Code Online (Sandbox Code Playgroud)

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

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

Nie*_*sol 8

既然你指定了jQuery,那么你去:

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

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

在简单的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,'-');
    }
})();
Run Code Online (Sandbox Code Playgroud)

更好的是,检查重复:

(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;
    }
})();
Run Code Online (Sandbox Code Playgroud)