天天看點

$.each()

$.each()與$(selector).each()不同, 後者專用于jquery對象的周遊, 前者可用于周遊任何的集合(無論是數組或對象),如果是數組,回調函數每次傳入數組的索引和對應的值(值亦可以通過this 關鍵字擷取,但javascript總會包裝this 值作為一個對象—盡管是一個字元串或是一個數字),方法會傳回被周遊對象的第一參數.

---------------------------------------------------

//例子:———傳入數組

<!DOCTYPE html>

<html>

<head>

<script src=”http://code.jquery.com/jquery-latest.js”></script>

</head>

<body>

<script>

$.each([52, 97], function(index, value) {

alert(index + ‘: ‘ + value);

});

</script>

</body>

</html>

//輸出

0: 52

1: 97

---------------------------------------------------

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//例子:———如果一個映射作為集合使用,回調函數每次傳入一個鍵-值對

<!DOCTYPE html>

<html>

<head>

<script src=”http://code.jquery.com/jquery-latest.js”></script>

</head>

<body>

<script>

var map = {

‘flammable’: ‘inflammable’,

‘duh’: ‘no duh’

};

$.each(map, function(key, value) {

alert(key + ‘: ‘ + value);

});

</script>

</body>

</html>

//輸出

flammable: inflammable

duh: no duh

---------------------------------------------------

//例子:———回調函數中 return false時可以退出$.each(), 如果傳回一個非false 即會像在for循環中使用continue 一樣, 會立即進入下一個周遊

<!DOCTYPE html>

<html>

<head>

<style>

div { color:blue; }

div#five { color:red; }

</style>

<script src=”http://code.jquery.com/jquery-latest.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 指定值

$(“#” + this).text(“Mine is ” + this + “.”); // this指向為數組的值, 如one, two

return (this != “three”); // 如果this = three 則退出周遊

});

jQuery.each(obj, function(i, val) { // i 指向鍵, val指定值

$(“#” + i).append(document.createTextNode(” – ” + val));

});

</script>

</body>

</html>

// 輸出

Mine is one. – 1

Mine is two. – 2

Mine is three. – 3

- 4

- 5

---------------------------------------------------

繼續閱讀