简体   繁体   中英

JQuery-Need help understanding (i, el)

I am having trouble understanding this piece of code.

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"); 
    } 
  });

});

I understand that the bottom half of the code runs when the window is scrolled and that both allMods.each blocks are loops that iterate over all the elements with the "module" class.

There are three things I don't understand:

  1. Shouldn't the .each function take in an array or object and a callback function as parameters? Here it just takes a function.
  2. 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.
  3. When does the block in the top half run? It is not inside the win.scroll event.

Shouldn't the .each function take in an array or object and a callback function as parameters? Here it just takes a function.

No. You are calling it as a method on a jQuery object. It is that object that it loops over. Internally each uses this to determine that.

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.

You can use whatever names you like for function arguments, it has no effect on what values are passed into it when it is called. Determining that is the responsibility of the calling function (ie the internals of each ). The values that are passed into them are described in the documentation for each .

Type: Function( Integer index, Element element )

The first argument is the index in the jQuery object. The second argument is the element that is the value of that index.

When does the block in the top half run? It is not inside the win.scroll event.

The same time any other code that isn't inside a function will run. When the script is loaded into the document.

  1. No. $().each() runs on a jQuery object (collection of elements) and only takes a function as a parameter.
  2. See the documentation linked above. i is the index (0-based) and el is the element itself. Yes, you can freely change the names as long as you change the references inside the function as well.
  3. It runs at startup, whenever that block of code gets executed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM