了解jQuery $ each()参数的来源?

the*_*der 6 parameters jquery function

在昨晚阅读jQuery Cookbook(Oreilly)的同时,我遇到了一个问题,这个问题似乎无法在书中找到答案,或者在网上找到答案.我在jQuery网站上找到了我用于此问题的代码,我在下面将其作为参考:

<script>
    $(document.body).click(function () {
      $("div").each(function (i) {            //Where does the 'i' come from?
        if (this.style.color != "blue") {
          this.style.color = "blue";
        } else {
          this.style.color = "";
        }
      });
    });
</script>
Run Code Online (Sandbox Code Playgroud)

我想知道'i'参数的起源和目的,因为我没有看到它来自哪里(客户端代码)以及它用于什么?作为一个Java人,我会更熟悉这个概念,因为我熟悉Java中的方法或"函数"参数.

在这里,我没有看到客户端代码(我认为它在库中)并且我没有看到它(/ i)在函数中是如何相关的,因为它没有被引用.

来自社区的人是否可以为此做出明确的解释或者请参考我的指南?

我理解每个函数的目的和'this'参考,所以你不需要解释这些,除非你觉得它与这个问题的未来观众有关.

Jam*_*ice 13

在那种情况下,没有必要申报i.该each方法的签名在jQuery文档中说明:

.each( function(index, Element) )

如您所见,它需要一个参数,该参数是一个带有2个参数的函数,indexElement.

在您的代码中,i是一个标识符index,每次调用时都会通过jQuery传递给回调函数(每次迭代一次).它还传递了第二个参数,但是您没有声明它的标识符,因此只能通过该arguments对象访问它.

您可以通过记录该arguments对象来确切地查看传递给回调的内容:

?$("div").each(function () { //No arguments listed in callback signature...
    console.log(arguments); //But arguments are still passed
});??
Run Code Online (Sandbox Code Playgroud)

这是上面的一个工作示例.

这是jQuery本身相关代码(添加评论):

//...
each: function( object, callback, args ) {
    //...

    //Iterate over the matched set of elements
    for ( ; i < length; ) {
        /* Call the callback in the context of the element, passing in the 
           index and the element */
        if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) {
            break;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)