【1】$().each(function(){})
-dom processing
For this method, use more on the DOM processing
If there are multiple input tags on the page, the type of INPUT tags is Checkbox, for at this time$().each
to process multiple Checkbook, for example::
$ ("input [name = 'ch']").
if ($ (this) .attr ("checked") == true) {
// Some operating code
}
}
Return function can pass the parameters, and Index is an index traversed.
【2】$.each(parentData,function(index,childData){})
For this method, the collection data processing is used more
parameter | description |
---|---|
function(index,element) | must. Run the function specified in each matching element. Index: Sexex position; Element: The current element (can also use the ‘this’ selector) |
var json = [{"name": "limeng", "email": "xfjylimeng"}, {"name": "hehe", "email": "fjylimeng"}]
$ .Each (json, function (index, data) {
Alert ("Index:"+Index+","+"corresponding value:"+data.name);
});
var obj = { one:1, two:2, three:3, four:4, five:5 };
$.each(obj, function(key, val) {
alert(obj[key]);
});
var arr1 = ["One", "TWO", "Three", "Four", "Five"];
$ .Each (Arr1, Function () {
alert (this);
});
Output: One Two Three Four Five
var arr2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]]
$ .Each (ARR2, Function (I, Item) {
alert (item [0]);
});
Output: 1 4 7
$.each(countyJson, function(index, data) {
if (data.parent == selValue) {
var option = "<option value='" + data.id + "'>" + data.county + "</option>";
$("#selDistrict").append(option);
}
});
Note that the json here is JS object, if it is a string, useJSON.parse()
or jquery$.parseJSON
Convert it to the JavaScript object.
var json = '[{"id":"1","tagName":"apple"},{"id":"2","tagName":"orange"},
{"id":"3","tagName":"banana"},{"id":"4","tagName":"watermelon"},
{"id":"5","tagName":"pineapple"}]';
$.each(JSON.parse(json), function(idx, obj) {
alert(obj.tagName);
});
//or
$.each($.parseJSON(json), function(idx, obj) {
alert(obj.tagName);
});
【3】array.forEach()
FOREACH () method is used to call each element of the array and pass the element to the callback function.
is traversed in JS, cannot traverse the object, the traversal object uses for in, or transforms the object into an array, and [] .slice.call (jQuery instance object);
Foreach’s callback function Function has three parameters. The first is that VAL is the current value of the array, the second index is the current value of the current value, and the third ARR is the original array;
FOREACH () No return value;
Note: Foreach () does not perform the callback function for the empty array.
grammar format is as follows:
array.forEach(function(currentValue, index, arr), thisValue)
parameter analysis is as follows:
Example is as follows:
var arr = [1,2,3,4];
Arr.Foreach (function (value, index, arr) {
Arr [index] = 2*Val;
});
console.log (ARR); // The result was modified the original array, which was multiplied by 2
The result is as follows: