jquery - 如何使用 jQuery .each 对匹配对象的子集进行不同的操作

标签 jquery each

我正在使用最新的 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/

相关文章:

javascript - 无法从 HTML 获取表值

jquery - 查找具有给定类和多个属性的元素 Jquery

javascript - $.each 在 $.append 里面(对象 [object Array] 没有方法 'apply' )

javascript - knockout.js 虚拟模板绑定(bind)

javascript - 将 jQuery 事件函数应用于新的 Knockout.js 数组元素

javascript - 从选择中删除特定父级的子级

javascript - Bootstrap 3 和 ScrollTop 函数 : #link conflict

css - 从 Console.log 中获取信息并显示在 div 中

javascript - 为什么 $.each 仅显示我的 Mustache 模板之一?

Jquery 将序列化数据放入数组