H3标签的内容作为H3的ID

3
我需要获取 <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>

页面上应该有许多h3标签,因此需要在某处包含“$this”。

希望这样说起来有意义 - 我对jQuery还好,但这个问题一直困扰着我。


4
你尝试过什么?这似乎很简单。你具体遇到了什么问题?这里有很多提示。例如 如何在 jQuery 中获取元素的文本值?将 JavaScript 字符串转换为全小写?用“+”替换字符串中所有空格 - Felix Kling
如果两个H3标签的内容相同怎么办?你想让它们拥有相同的ID吗?这不是有效的HTML。 - Shyju
当然,使用jQuery更改元素的ID(https://dev59.com/wnRC5IYBdhLWcg3wSu97)。 - Felix Kling
2个回答

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

@Christoph 是的,但这是不太明显和不必要的,因为NodeList没有从中删除元素。 - Niet the Dark Absol
这太完美了,谢谢,还有一些我在 StackOverflow 上没找到的东西,希望对其他人有所帮助。 - John the Painter
@Christoph Erm,每次循环迭代时都会重新检查长度,因此缓存它可以节省大量时间。 - Niet the Dark Absol
@Kolink 如果你有几百万个标题的话,那就是真的了;) - Christoph
尽管如此,我还是给你点赞,因为我真的很喜欢你的双重解决方案。 - Christoph
显示剩余2条评论

1
一个解决方案:
$("h3").each(function() {

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

});

"一个解决方案",但不是一个好的解决方案。如果标题中包含除空格字符之外的空格,怎么办?如果多个标题在此方式转换时具有相同的文本内容怎么办? - Niet the Dark Absol

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接