本文跟大家分享jquery中map函數的兩種方式,非常不錯,具有參考借鑒價值,需要的朋友參考下吧
兩種方式:
1、直接jQuery.map
#
1 2 3 4 5 6 7 8 9 10 11 12 | $.map( [0,1,2], function (n){
return n + 4;
});
[4, 5, 6]
$.map( [0,1,2], function (n){
return [ n, n + 1 ];
});
[0, 1, 1, 2, 2, 3]
|
登入後複製
2、遍歷物件.map
範例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <form method="post" action="">
<fieldset>
<p>
<label for ="two">2</label>
<input type="checkbox" value="2" id="two" name="number[]">
</p>
<p>
<label for ="four">4</label>
<input type="checkbox" value="4" id="four" name="number[]">
</p>
<p>
<label for ="six">6</label>
<input type="checkbox" value="6" id="six" name="number[]">
</p>
<p>
<label for ="eight">8</label>
<input type="checkbox" value="8" id="eight" name="number[]">
</p>
</fieldset>
</form>
$(':checkbox').map( function () {
return this.id;
}).get().join(',');
|
登入後複製
結果:two,four,six,eight
解析:
map()的功能主要有兩步, 第一步就是遍歷,第二步就是替換。
1 2 3 | $( " li " ).map( function (){
return $(this).text();
})
|
登入後複製
map先遍歷,每一項都會傳回一個text()值,然後map會將這些值自動去替換$("li")集合的每一項值,所以這個時候還是個類別數組(因為還是$(" li ")的殼子),不是真正的陣列。於是後面加個get()操作就變成真正的陣列了,於是可以用join()這樣專屬於陣列的方法。
以上是jQuery中關於map函數兩種方式的範例程式碼的詳細內容。更多資訊請關注PHP中文網其他相關文章!