欢迎来到cool的博客
7

Music box

Click to Start

点击头像播放音乐
新博客链接

jquery .each() function 对元素,数组,json

参考文档:https://www.sitepoint.com/jquery-each-function-examples/

 

2. jQuery.each() Array Example

Let’s have another look at how an ordinary array can be handled.

var numbers = [1, 2, 3, 4, 5, 6];
$.each(numbers , function (index, value){
  console.log(index + ':' + value); 
});

This snippet outputs: 0:11:22:33:44:5, and 5:6.

Nothing special here. An array features numeric indices, hence we obtain numbers starting from 0 and going up to N – 1, where N is the number of elements in the array.

3. jQuery.each() JSON Example

We may have more complicated data structures, such as arrays in arrays, objects in objects, arrays in objects, or objects in arrays. Let’s see how each() can help us in such scenarios.

var json = [ 
 { 'red': '#f00' },
 { 'green': '#0f0' },
 { 'blue': '#00f' }
];

$.each(json, function () {
   $.each(this, function (name, value) {
      console.log(name + '=' + value);
   });
});

This example outputs red=#f00green=#0f0blue=#00f.

We handle the nested structure with a nested call to each(). The outer call handles the array of the variable JSON, the inner call handles the objects. In this example each object has only one key, however, in general any number could be attacked with the provided code.

4. jQuery.each() Class Example

This example shows how to loop through each element with assigned class productDescription given in the HTML below.

<div class="productDescription">Red</div>
<div>Pink</div>
<div class="productDescription">Orange</div>
<div class="generalDescription">Teal</div>
<div class="productDescription">Green</div>

We use the each() helper instead of the each() method on the selector.

$.each($('.productDescription'), function (index, value) { 
  console.log(index + ':' + $(value).text()); 
});

In this case the output is 0:Red1:Orange2:Green.

We don’t have to include index and value. These are just parameters which help determine on which DOM element we are currently iterating. Furthermore, in this scenario we can also use the more convenient each method. We can write it like this:

$('.productDescription').each(function () { 
  console.log($(this).text());
});

And we’ll obtain on the console:

Red
Orange
Green

Again, we need to wrap the DOM element in a new jQuery instance. We use the text() method to obtain the element’s text for output.

返回列表