我正在使用最新的 jQuery(通过 Google CDN)并使用此代码构建目录:
$("#infoArticles h2, #infoArticles h3").each(function(i) {
var current = $(this);
current.attr("id", "title" + i);
$("#toc").append("<li><a id='link" + i + "' href='#title" + i + "' title='" + current.attr("tagName") + "'>" + current.html() + "</a></li>");
});
工作很愉快。
我希望 .each 循环以不同的方式对待匹配的 h2 和匹配的 h3,以便我可以向 h2 生成的 li 添加一个类。
任何有用的评论,我们深表感谢!
最佳答案
$("#infoArticles h2, #infoArticles h3").each(function(i) {
var current = $(this);
current.attr("id", "title" + i);
if(this.tagName == "H2"){
//h2
}else{
//h3
}
$("#toc").append("<li><a id='link" + i + "' href='#title" + i + "' title='" + current.attr("tagName") + "'>" + current.html() + "</a></li>");
});
关于jquery - 如何使用 jQuery .each 对匹配对象的子集进行不同的操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1954209/