以下全是官網範例:
$.each(jQuery.each()):
http://api.jquery.com/jquery.each/ (官網範例):
array:
$.each([ 52, 97 ], function( index, value ) { alert( index + ": " + value );});output:
0:52
1:97
Json:
var obj = { "flammable": "inflammable", "duh": "no duh"};$.each( obj, function( key, value ) { alert( key + ": " + value );});output:
flammable : inflammable
duh : no duh
兩種加一起:
<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( i, val ) { $( "#" + val ).text( "Mine is " + val + "." ); // Will stop running after "three" return ( val !== "three" ); // 這邊只要等於false時就離開each迴圈});jQuery.each( obj, function( i, val ) { $( "#" + i ).append( document.createTextNode( " - " + val ) );});</script></body>
備註:document.createTextNode:
document.createTextNode() 方法 (method) 替文件物件 (object) 新增文字節點。
function run() { var t = "There is no spoon." var d = document.createTextNode(t); var s = document.getElementById("show"); s.appendChild(d);}<body> <input type="button" value="RUN" onclick="run();"> <div id="show"></div></body>createTextNode() 說明網址: http://pydoing.blogspot.tw/2011/08/javascript-createtextnode.html
.each (Ex:$("li").each())
http://api.jquery.com/each/ (官網範例)
<body>
<ul>
<li>foo</li>
<li>bar</li>
</ul>
</body>
<script>
$("li").each(function(index) {
alert(index + ": " + $(this).text());
});
</script>
output:
0:foo
1:bar
ps: 網站有提到:You can stop the loop from within the callback function by returning false.
<style>
.example {
font-style: italic;
}
</style>
<body>
<ul>
<li>foo</li>
<li>bar</li>
</ul>
To do list: <span>(click here to change)</span> <ul> <li>Eat</li> <li>Sleep</li> <li>Be merry</li></ul></body>
<script>
$("span").click(function() {
$("li").each(function() {
$(this).toggleClass("example");
});
});
</script>
output:
foo、bar、Eat、Sleep、Be merry 都會變為 example的css格式
