我需要获取<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没意见,但这给我带来了一些问题。
发布于 2012-07-23 21:27:57
由于您指定了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;
}
})();发布于 2012-07-23 21:30:42
一种解决方案:
$("h3").each(function() {
var content = $(this).html().replace(/ /g,'_').toLowerCase();
$(this).attr("id",content);
});https://stackoverflow.com/questions/11613435
复制相似问题