javascript - JQuery-需要帮助理解 (i, el)

标签 javascript jquery web

我无法理解这段代码。

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”类的所有元素。

有三件事我不明白:

  1. .each 函数不应该接受数组或对象和回调函数作为参数吗?这里它只需要一个函数。
  2. 为什么“i”和“el”作为参数传递给函数。我猜测“el”指的是当前正在迭代的元素,但为什么他们称其为“el”。您可以将所有“el”替换为任何其他名称吗?我不知道“我”是什么。
  3. 上半部分的 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/

相关文章:

jQuery - 将事件附加到动态元素

javascript - REACT JavaScript 如何使用自定义类名?

javascript - 发生 ajax 请求时运行代码的 Chrome 扩展

javascript - 从 Node.js 向 MongoDB 集合插入不同类型的值

javascript - 从地理位置字符串中提取纬度/经度

jquery - 如何动态设置视口(viewport)?

javascript - Selenium 与 NodeJS - 从 TinyMCE iframe 返回时驱动程序对象丢失上下文

jquery - 如何知道 $(window).load();来自 jquery 的状态

javascript - 如何使用 JQuery 创建输入建议

html - 如何停止下拉列表出现在列表项的顶部