以下全是官網範例:

$.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 };
 
// 下面這一行的function(i,val) 就看成function(index , value)
jQuery.each( arr, function( i, val ) {
$( "#" + val ).text( "Mine is " + val + "." );
 
// Will stop running after "three"
return ( val !== "three" ); // 這邊只要等於false時就離開each迴圈
});
 
// 下面這行 function(i,val) 就看成function(key , value)
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>
 
 
output:
 
[button]
There is no spoon.

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格式

 

 

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 JoshS 的頭像
    JoshS

    JoshS的部落格

    JoshS 發表在 痞客邦 留言(0) 人氣()