我无法理解这段代码。
var win = $(window);
var allMods = $(".module");
// Already visible modules
allMods.each(function(i, el) {
var el = $(el);
if (el.visible(true)) {
el.addClass("already-visible");
}
});
win.scroll(function(event) {
allMods.each(function(i, el) {
var el = $(el);
if (el.visible(true)) {
el.addClass("come-in");
}
});
});
我知道代码的下半部分在窗口滚动时运行,并且两个 allMods.each block 都是循环遍历具有“module”类的所有元素。
有三件事我不明白:
- .each 函数不应该接受数组或对象和回调函数作为参数吗?这里它只需要一个函数。
- 为什么“i”和“el”作为参数传递给函数。我猜测“el”指的是当前正在迭代的元素,但为什么他们称其为“el”。您可以将所有“el”替换为任何其他名称吗?我不知道“我”是什么。
- 上半部分的 block 什么时候运行?它不在 win.scroll 事件内。
最佳答案
Shouldn't the .each function take in an array or object and a callback function as parameters? Here it just takes a function.
没有。您将其作为 jQuery 对象的方法进行调用。它循环的就是那个对象。在内部,each
使用 this
来确定。
Why are "i" and "el" being passed in as parameters to the function. I'm guessing "el" refers to the current element being iterated over, but why did they call it "el". Could you replace all the "el"s for any other name? I have no idea what "i" is.
您可以为函数参数使用任何您喜欢的名称,它对调用时传递给它的值没有影响。确定这是调用函数的责任(即each
的内部)。 the documentation for each
中描述了传递给它们的值。 .
Type: Function( Integer index, Element element )
第一个参数是 jQuery 对象中的索引。第二个参数是作为该索引值的元素。
When does the block in the top half run? It is not inside the win.scroll event.
同时,不在函数内部的任何其他代码都会运行。当脚本加载到文档中时。
关于javascript - JQuery-需要帮助理解 (i, el),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37308563/