2009-11-03 78 views
0

我正在通过函数each()在同一个类中循环多个复选框,在循环内我需要能够判断复选框是否被选中。怎么做?是否勾选复选框(在每个()循环中)?

$('.checkbox').each(function() { 
    var is_checked = 'no'; 
    // I need to change the value of the is_checked variable to 'yes' 
    // if the checkbox is checked 
    // 
}); 

回答

5

使用

var is_checked = this.checked ? 'yes' : 'no'; 
4

一种方法是:

$('#yourcheckbox').is(':checked'); 
+0

这是真的,但是比只说'this.checked'更难阅读和更慢。您不必为所做的每件事情都使用jQuery语法,DOM仍然存在。 – bobince 2009-11-03 22:28:38

+0

当然,我试图将它保存在他已有的jquery代码中,但你说得对。这个.checked可能更快,更简单。 – 2009-11-05 08:59:03

3

为什么不改用:checkbox:checked选择?这样您可以获得所有选中的复选框的列表并对这些复选框进行迭代。

1

这将让所有选中复选框

$("input:not(:checked)") 
1

相信$(this).val()会给你 “真” 如果选中,然后$(this).val("true")将设定值

2
$("input:checkbox[class='.checkbox']:checked").each(function() { 
// this will only loop thru checked boxes (checked = true) 
} 

OR

$('.checkbox').each(function() {  
// or return a boolean for each one 
var is_checked = $(this).is(":checked"); 
});