jquery 的 for 循環:
1、 var userList = [11,22,33,44];
$.each(userList,function(i,item){
console.log(i, item);
});
結果輸出:
0 11
1 22
2 33
3 44
用法: $.each() 第一個參數是循環的對象 , 第二個參數對對象中的每一個元素 執行 function函數 ,function 的第一個參數 i 是索引,item 是 循環對象中的每一個元素。
一般的寫法: for(var i in userList){} 這里面的 i 是 索引。
如果循環對象是 字典,上面的 i, item 分別是 key , value 。
2、 如果有一個 table 包含多個 tr , 每個 tr 包含多個 td , td 中 有 checkbox 。如果要循環 checkbox 。可以用以下的寫法:
function ReverseAll(){
$('table :checkbox').each(function(){
var isChecked = $(this).prop('checked'); // $(this) 獲取當前的循環對象,此例中表示 table 中的 checkbox 子元素 集合中的一個元素
if(isChecked) { $(this).prop("checked",false); }
else{ $(this).prop("checked",true); }
}) ;
} //此函數實現對 table表中所有的checkbox 反選功能。
此處用 $('table :checkbox') 選擇器 獲取的 table 對象中的所有 checkbox 子元素,並且對每個子元素 執行 function 。是一種鏈式編程。