jQuery each函数中的index参数是什么意思?

3

我很好奇为什么需要这个索引。

$(document).ready(function() {
        $(".divToggle").each(function(index){
            var buttonId = $(this)[0].attributes["id"].value.toString();
            var idParts = buttonId.split('_');
            var uniquePart = idParts[0] + "_" + idParts[1] + "_" + "divContentPanel";             
            $(this).click(function() {
                 $("#" + uniquePart).toggle("slow");
            });            
        });
    });

为什么在"var buttonId = $(this)[0]…"中需要"[0]"?如果没有它,我会得到一个attributes["id"]为空的错误。
6个回答

4

请使用这个替代方案

var buttonId = this.id;

或者使用jQuery的方式
var buttonId = $(this).attr("id");

2
$(this)[0]

这段代码主要有两个作用:

  1. 在循环匹配结果时,获取第一个元素。在这种情况下,索引可能是多余的。
  2. 返回一个“普通”的JavaScript DOM对象而不是一个jQuery包装的对象。

根据您的代码,我认为您可以通过以下方式实现相同的结果 -

var buttonId = this.id;

2

使用 $(this) 时,您仍处于 jQuery 模型中,正确获取 id 的方式是 .attr("id")。

写 $(this)[0] 会将您带回到 DOM 模型中,就像您所写的那样。


1

尝试

 var buttonId = $(this).attr("id");

1

从技术上讲,只需稍微修改您的代码即可不需要它。jQuery选择器的作用是将一堆元素引用存储在数组中。因此,可以使用以下方式代替:

<div id ="myelement"></div>

你得到了

[<div id ="myelement"></div>]

使用$(this)this放入数组中,并允许它与jQuery函数一起使用。如果您不使用jQuery函数,只需使用this即可。因此,您的代码将变为

var buttonId = this.attributes["id"].value.toString();

1
$(".divToggle").each(function(index, element){
    var buttonId = element.id,
        idParts = buttonId.split('_'),
        uniquePart = idParts[0] + "_" + idParts[1] + "_" + "divContentPanel";

    $(element).click(function() {
         $("#" + uniquePart).toggle("slow");
    });            
});

这是一个非常棒的解决方案,实际上这就是我在我的代码中最终使用的。谢谢。 - esastincy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接