2012-06-21 47 views
0

我在正确的道路上使用它吗?我正在改变我的做法,因为这样做效果最好。循环访问数组以检查复选框

我在做什么正在采取的一系列数字

var n = "1,3,8,12,2,19"; 

我已在检查的复选框以下内容:

$('#chk1').attr('checked', true) 

有没有办法用数字来代替1 CHK1旅店?我想循环访问数字数组,并检查具有该数字的所有框。

+0

“我想遍历数组数组”然后把它作为一个数组 – PeeHaa

回答

2

尝试像下面,

$.each (n.split(','), function (index, value) { 
    $('#chk' + value).attr('checked', true); 
}); 

如果你有n像下面这是比较容易,

var n = [1, 3, 8, 12, 2, 9];//array 
$.each (n, function (index, value) { 
    $('#chk' + value).attr('checked', true); 
}); 
0
var nums = n.split(','); 

$(nums).each(function(){ 
    $('#chk' + this).attr('checked', true); 
}); 
2
var n = "1,3,8,12,2,19", // not an Array but a String 
    arr = n.split(','); // now it turns to Array like [1, 3, 8, 12, 2, 9] 

// loop over array 
for(var i = 0 ; i < arr.length; i++) { 
    $('#chk' + arr[i]).attr('checked', true); 
} 
0

VAR NUMS = [1,3,8,12, 2,19]; (函数(){('#chk'+ this).prop''checked',true); });