jQuery.each() learn and conclusion
jQuery.each( collection, callback(indexInArray, valueOfElement) )
Returns: Object
Description:
A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties.
-
version added: 1.0 jQuery.each( collection, callback(indexInArray, valueOfElement) )
collectionThe object or array to iterate over.
callback(indexInArray, valueOfElement)The function that will be executed on every object.
The $.each()
function is not the same as .each(), which is used to iterate, exclusively, over a jQuery object. The $.each()
function can be used to iterate over any collection, whether it is a map (JavaScript object) or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time. (The value can also be accessed through the this
keyword, but Javascript will always wrap the this
value as an Object
even if it is a simple string or number value.) The method returns its first argument, the object that was iterated.
$.each([52, 97], function(index, value) {
alert(index + ': ' + value);
});
This produces two messages:
0: 52
1: 97
If a map is used as the collection, the callback is passed a key-value pair each time:
var map = {
'flammable': 'inflammable',
'duh': 'no duh'
};
$.each(map, function(key, value) {
alert(key + ': ' + value);
});
Once again, this produces two messages:
flammable: inflammable
duh: no duh
We can break the $.each()
loop at a particular iteration by making the callback function return false
. Returning non-false is the same as a continue
statement in a for loop; it will skip immediately to the next iteration.
Examples:
Example: Iterates through the array displaying each number as both a word and numeral
<!DOCTYPE html>
<html>
<head>
<style>
div { color:blue; }
div#five { color:red; }
</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<div id="one"></div>
<div id="two"></div>
<div id="three"></div>
<div id="four"></div>
<div id="five"></div>
<script>
var arr = [ "one", "two", "three", "four", "five" ];
var obj = { one:1, two:2, three:3, four:4, five:5 };
jQuery.each(arr, function() {
$("#" + this).text("Mine is " + this + ".");
return (this != "three"); // will stop running after "three"
});
jQuery.each(obj, function(i, val) {
$("#" + i).append(document.createTextNode(" - " + val));
});
</script>
</body>
</html>
Example: Iterates over items in an array, accessing both the current item and its index.
$.each( ['a','b','c'], function(i, l){
alert( "Index #" + i + ": " + l );
});
Example: Iterates over the properties in an object, accessing both the current item and its key.
$.each( { name: "John", lang: "JS" }, function(k, v){
alert( "Key: " + k + ", Value: " + v );
});
==================================================================================
1、第一种遍历选择器结果列表.
以每一个匹配的元素作为上下文来执行一个函数.例如:
页面html代码如下:
<ul id="u">
<li>111</li>
<li>sss</li>
</ul>
使用jquery遍历ul下的li标签
$("#u li").each(function(i,obj){
$(this).html($(this).html()+i); //其中obj 就是this
var arr1 = [ "one", "two", "three", "four", "five" ];
$.each(arr1, function(){
alert(this);
});
输出:
one two three four five
var arr2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
$.each(arr2, function(i, item){
alert(item[0]);
});
输出:
1 4 7
var obj = { one:1, two:2, three:3, four:4, five:5 };
$.each(obj, function(key, val) {
alert(obj[key]);
});
输出:
1 2 3 4 5
$.each($("input:hidden"), function(){
alert(this.name);
});
$.each($("input:hidden"), function(){
alert(this.value);
});
意味着,每次执行传递进来的函数时,函数中的this关键字都指向一个不同的DOM元素(每次都是一个不同的匹配元素)。
而且,在每次执行函数时,都会给函数传递一个表示作为执行环境的元素在匹配的元素集合中所处位置的数字值作为参数(从零开始的整形)。
返回 'false' 将停止循环 (就像在普通的循环中使用 'break')。返回 'true' 跳至下一个循环(就像在普通的循环中使用'continue')。
2、通用例遍方法,可用于例遍对象和数组
var data = [0,1,2];
$.each( data, function(i, value){
alert( "Item #" + i + ": " + value );
});
不同于例遍 jQuery 对象的 $().each() 方法,此方法可用于例遍任何对象。
==========================================================================
JS Unit Testing with jQuery and Qunit
For those that like to do test-driven development, even in javascript, then you might be more than interested to learn about Qunit. Qunit is a test suite developed by the team at jQuery for their own use and which they have of course made available for others to use. And the great thing about it? All you need to get started is a JS and CSS file + a bit of HTML, of course!
To get things kicked off the jQuery team provides access to a slew of their pre-existing tests, which can be downloaded and included as part of the range of your own tests, from AJAX, to dimensions, to events, to selector tests. You can find these tests are under the Reference Test Suites on the Qunit docs page of the jQuery website. They provide good fodder and resource for developing your own tests and ideas for them as well and are definitely worth a review for anyone just starting out in JS development and wanting to learn more about unit testing.
So what do you need to get started with jQuery Unit Testing? To begin with download both of the following files, Qunit.js, & Qunit.css, and include them in the head of your HTML document along with the latest version of jQuery. Then add the following HTML to the body of your document so that Qunit can render the test results properly:
2 |
< h1 id = "qunit-header" >QUnit example</ h1 > |
3 |
< h2 id = "qunit-banner" ></ h2 > |
4 |
< h2 id = "qunit-userAgent" ></ h2 > |
5 |
< ol id = "qunit-tests" ></ ol > |
As you can see, getting set up with a basic testing environment is easy and pretty simple. With this set-up you can then include your own Qunit tests either in a SCRIPT tag or in your own JavaScript external include.
So now you’re ready to start writing your own tests, lets keep it clean and simple. The unit testing API is split into 3 sections:
- Setup – The basics for defining tests, grouping them and getting them started.
- Assertions – The Yay and the Nay of whether conditions have the met with boolean tests, comparison tests and recoursive comparison assertions for arrays, objects, etc.
- Asynchronous Testing – Functions to stop and start the test runner.
Putting this together – not that we have looked in depth thus far – a very basic unit test would look as follows:
2 |
module( "Initial Test Module" ); |
3 |
test( "Test with multiple assertions" , function () { |
4 |
expect(2); |
5 |
equals( true , false , "failing test" ); |
6 |
equals( true , true , "passing test" ); |
7 |
}); |
Deconstructing the above test. “Module” provides a means by which to delineate individuals sets of unit tests. The “test” function with title and callback function params includes 2 further functions: “expect” and “equals”. The former sets the expectation for the number of assertions that have been defined and follow, whilst the latter obviously does the grunt work and returns the results. In defining an assertion you need to provide 3 things:
- The expected result.
- The result.
- An error message.
As you can see writing even the most basic tests is super simple and pretty much a no-brainer. Adding complexity to the mix, with more test modules, multiple test and assertions interlinked and daisy chained together makes for a powerful brew.
To my mind there is little point in re-inventing the wheel, especially when so many good test examples exist, and which you can draw on for ideas in your own testing, but I thought it might be worth highlighting various points that can add flavour to your unit tests:
- “Module” provides lifecycle hooks for running code on setup and teardown of each test and you can just as easily bind tests to functions and events via jQuery also. Good examples exist in the actual jQuery core tests for the AJAX calls (core.js, ajax.js, etcetera).
- Daising chaining your assertions together makes for useful testing when wishing to assert that different types of scenarios, for example when making invalid requests to an AJAX web service with illegal characters, insufficient parameters, unauthorised params etc will fail properly, and thus pass your tests accordingly. Definitely worth using when testing forms and data entry.
- Manipulate the DOM and everything else has much as possible during the course of your tests. Alter the underlying code and test for the results as you go. You shouldn’t be afraid to try and break things and test against them. It’s very easy to get into the developer mindset where you know how they should work, and you are can make them work perfectly all the time.