Jquery H3的内容作为H3';身份证
我需要获取Jquery H3的内容作为H3';身份证,jquery,html,Jquery,Html,我需要获取的内容,然后将内容小写并删除空格(将其替换为-or),然后将其插入的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> 关于这个东西 关于这些东西 这应
的内容,然后将内容小写并删除空格(将其替换为-or),然后将其插入
的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>
关于这个东西
希望这是有意义的-我对jQuery没什么意见,但这给我带来了一些问题。自从您指定了jQuery之后,接下来就是:
$("h3").each(function() {
var me = $(this);
me.attr("id",me.text().toLowerCase().replace(/[^a-z0-9-]/g,'-').replace(/--+/g,'-'));
});
这将用-
替换所有非字母数字字符,然后去掉多个连续的-
字符
在普通JS中(效率更高):
(函数(){
var tags=document.getElementsByTagName(“h3”),l=tags.length,i;
对于(i=0;iA溶液:
$("h3").each(function() {
var content = $(this).html().replace(/ /g,'_').toLowerCase();
$(this).attr("id",content);
});
你试过什么?看起来很简单。你到底有什么问题?这里有很多提示。例如,如果2 H3有相同的内容怎么办?你想要两个都有相同的ID吗?这当然不是有效的HTMLAnd。@Christoph是的,但这不太明显,也不必要,因为节点列表没有删除元素d。这很完美,谢谢,还有我在StackOverflow上没有找到的东西,希望它能对其他人有所帮助。@Christoph Erm,每次循环迭代时都会重新检查长度,因此缓存它可以非常节省时间。@Kolink true,如果你有几百万个标题;)@Christoph鼓吹纯JavaScript比jQuery更高效,然后使用低效的做法是有点虚伪的:P“一个解决方案”,是的,但很糟糕。如果标题包含空格而不仅仅是空格字符,会怎么样?如果以这种方式转换时多个标题具有相同的文本内容会怎么样?
(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;
}
})();
$("h3").each(function() {
var content = $(this).html().replace(/ /g,'_').toLowerCase();
$(this).attr("id",content);
});