开发者

in jquery, what does $.each mean?

开发者 https://www.devze.com 2022-12-17 01:45 出处:网络
what does the following mean? $.e开发者_Python百科ach(json.results, function(i, item) { ... } I kind of understand the other parts of the line, but if you could explain that as well, I\'d appreciat

what does the following mean?

$.e开发者_Python百科ach(json.results, function(i, item) {
    ...
}

I kind of understand the other parts of the line, but if you could explain that as well, I'd appreciate it.


$.each provides a simple iterator and it will execute the callback function once for each element in the array.

For my examples, lets assume:

var json = {
   results: [1, 2, 3]
};

In addition to using the parameters (index, item), the this variable in each callback can be used to reference the current item.

UPDATE: This example changed to show use of the other parameters:

$.each( json.results, function(index, item){
   console.log(this + " " + index + " " + item);
});
// Outputs:
// 1 0 1
// 2 1 2
// 3 2 3

The first parameter is the index of the current item in the loop. It is a zero based index. The second parameter is the item of the current iteration. You can use this or the variable, but the variable comes in handy in situations like this:

$.each (json.results, function(index, item){
   // this == number
   // item == number
   $('div').click(function(e){
      // this == div
      // item == number
   });
});

Additionally, there are a few controls you can use similar to the break and continue statements.

If you want to continue or next at any point, use return true;

$.each( json.results, function(i, item){
  if(this == 2) return true;
  // do something else
});

If you want to break, use return false;

var f;
$.each( json.results, function(i, item){
   if(this == 2){
      f = this;
      return false; // exits the iterator
   }
});


It just means you want to do something with each result found in json.results. Within the curly-braces, the current result you're handling is known by this, so you could do something like:

var json = { 'results':{'name':'jonathan', 'age':'26'} };

$.each(json.results, function(i,o){
  alert(this);
  // First iteration : 'Jonathan'
  // Second Iteration: '26'
});


$.each is basically an iteration idiom, similar to javascripts:

for (x in container)

except it iterates over values, instead of keys (or indices in the array case).


It iterates over the members of an object. An example:

var obj = {
    alpha : 'A',
    beta : 'B',
    3 : 'C'
};

$.each(obj, function(key, val) {
    console.log(key);    // alpha, beta, 3
    console.log(val);    // A, B, C
    console.log(this);   // A, B, C
});

Edit: Actually the above is a bad example of the context of this, because if your value is a string or number, it's converted from the literal ("C") to an object (new String("C")), but for other things (functions, elements, arrays, etc) it's untouched.

0

精彩评论

暂无评论...
验证码 换一张
取 消