我正在尝试获取一个复选框来选中和取消选中它是否未选中/已选中。它正在检查是否未选中 - 但如果已选中则不会取消选中。很奇怪。提前致谢!
这是我的代码:
编辑: 这是 jsfiddle:http://jsfiddle.net/itamark/UnR4X/
JS:
$(':checkbox').mouseenter(function(){
if($(this).not(':checked')) {
alert('notchecked');
$(this).attr('checked', true);
}
else if($(this).is(':checked')){
alert('ischecked');
$(this).attr('checked', false);
}
})
HTML:
<input type="checkbox" name"myCheck" id="chk1"/>Checkbox</label>
最佳答案
.is()
和 .not()
不一样
.is()
返回 true 或 false 而 .not()
如果匹配则移除 jQuery 元素。
因此,$(selector).not()
将始终为真,因为 jquery 已定义。
要检查元素是否存在,使用.length
。
$(':checkbox').hover(function(){
if($(this).not(':checked').length) {
$(this).prop('checked', true);
}
else if($(this).is(':checked')){
$(this).prop('checked', false);
}
})
fiddle :http://jsfiddle.net/UnR4X/3/
你也可以使用 1 衬垫:
$(this).prop('checked', !$(this).prop('checked'));
关于javascript - 使用 Jquery 选中和取消选中复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18025802/