如何使用 jQuery .each 对匹配对象的子集进行不同的操作
我正在使用最新的 jQuery(通过 Google CDN),并使用此代码来构建 TOC:
$("#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 添加一个类。
任何有用的意见,我们将不胜感激并深表感谢!
I'm using latest jQuery (via the Google CDN) and am using this code to build a TOC:
$("#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>");
});
Works a treat.
I want the .each loop to treat matched h2's differently from matched h3's in order that I may add a class to the li's resulting from h2's.
Any helpful comments, most appreciated and gratefully received!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
更多
发布评论
评论(4)
检查
nodeName
或tagName
。Check the
nodeName
ortagName
.您从代码中创建一个函数并使用不同的参数调用它:
You create a function out of your code and call it with different parameters:
请注意,Append 的成本很高,因此,为了优化,您应该将append() 函数移出循环,只执行一次,而不是针对每个选定的元素执行一次。
Note that Append is expensive, so, for the sake of optimisation, you should move the append() function out of your loop, to only do it once instead of for each selected element.