2

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

任何有用的意见,非常感谢和感激地接受!

4

4 回答 4

1

检查nodeNametagName

$("h2").each(function(i){
  alert(this.nodeName + " " + i); // Alerts 'H2 0,' 'H2 1,' etc.
});
于 2009-12-23T17:35:57.057 回答
1
$("#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>");
});
于 2009-12-23T17:37:09.457 回答
0

请注意,Append 很昂贵,因此,为了优化,您应该将 append() 函数移出循环,只执行一次,而不是针对每个选定元素执行一次。

var htmlToInsert = null;
$("#infoArticles h2, #infoArticles h3").each(function(i) {
    var current = $(this);
    current.attr("id", "title" + i);
    if(this.tagName == "H2"){
      //h2
    }else{
      //h3
    }
    htmlToInsert += "<li><a id='link" + i + "' href='#title" + i + "' title='" + current.attr("tagName") + "'>" + current.html() + "</a></li>";

});
$("#toc").append(htmlToInsert);
于 2009-12-23T17:41:45.387 回答
0

您从代码中创建一个函数并使用不同的参数调用它:

$("#infoArticles h2").each(function(i) {
    myFunction("ma-classe");
});
$("#infoArticles h3").each(function(i) {
    myFunction();
});

function myFunction(class=""){
   var current = $(this);
    current.attr("id", "title" + i);
    $("#toc").append("<li class='"+class+"'><a id='link" + i + "' href='#title" + i + "' title='" + current.attr("tagName") + "'>" + current.html() + "</a></li>");
}
于 2009-12-23T17:39:23.287 回答