昨晚在阅读 jQuery Cookbook (Oreilly) 时,我遇到了一个 every 函数,它产生了一个问题,我似乎无法在书中或在线找到答案。 我用于这个问题的代码可以从 jQuery site 找到。我将其包含在下面作为引用:
<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>
我想知道“i”参数的起源和用途,因为我看不到它来自哪里(客户端代码)以及它的用途是什么?作为一名 Java 人员,我会更容易地掌握这个概念,因为我熟悉 Java 上下文中的方法或“函数”参数。
在这里,我没有看到客户端代码(我假设它在库中),并且我没有看到它(i
)在函数中如何相关,因为它没有被引用。
社区中的有人可以对此给出明确的解释或向我推荐相关指南吗?
我了解每个函数和“this”引用的用途,因此您无需解释这些内容,除非您认为它们与此问题的 future 查看者相关。
最佳答案
在这种情况下,无需声明i
。 each
method的签名jQuery 文档中指出:
.each( function(index, Element) )
如您所见,它需要一个参数,而该参数是一个需要 2 个参数的函数:index
和 Element
。
在您的代码中,i
是 index
的标识符,每次调用时都会由 jQuery 传递给回调函数(每次迭代一次)。它还传递第二个参数,但您尚未为其声明标识符,因此只能通过 arguments
访问它。对象。
您可以通过记录该 arguments
对象来准确查看传递给回调的内容:
$("div").each(function () { //No arguments listed in callback signature...
console.log(arguments); //But arguments are still passed
});
这是一个working example以上。
这是relevant code from jQuery itself (已添加评论):
//...
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;
}
}
}
关于jquery - 了解 jQuery $each() 参数的起源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11096648/