谁能解释一下,为什么我们需要each(function (i)
(i)
是做什么的?似乎 i
可以是任何字母。
为什么 (i)
是必要的?我不太明白。非常感谢
<body>
<div>Click here</div>
<div>to iterate through</div>
<div>these divs.</div>
<script>
$(document.body).click(function () {
$( "div" ).each(function (i) {
if ( this.style.color != "blue" ) {
this.style.color = "blue";
} else {
this.style.color = "";
}
});
});
</script>
最佳答案
回调函数的第一个参数是循环中迭代的索引。即循环计数器。在您的情况下,您根本不需要它,因为您没有使用它:
$("div").each(function() {
if (this.style.color != "blue") {
this.style.color = "blue";
} else {
this.style.color = "";
}
});
第二个参数是当前迭代的元素,即与 this
所指的相同。您可以使用该参数代替 this
。当然,要使用第二个参数,您还必须指定第一个参数,即使您不使用它也是如此:
$("div").each(function(i, e) {
if (e.style.color != "blue") {
e.style.color = "blue";
} else {
e.style.color = "";
}
});
关于javascript - 基本的 jQuery 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14206448/