我希望能够通过单击其父 DIV 来选中和取消选中复选框。
html:
<div class="insurance-option-select">
<input name="insurance[Auto]" type="checkbox" value="1">
</div>
<div class="insurance-option-select">
<input name="insurance[Home]" type="checkbox" value="2">
</div>
js:
$('.insurance-option-select').on('click', function () {
if ($(this).find('input').prop('checked')) {
$(this).find('input').removeAttr('checked');
} else {
$(this).find('input').attr('checked', true);
}
});
CSS:
.insurance-option-select {
background: red;
padding: 30px;
margin: 30px auto;
}
.insurance-option-select:hover {
background: green;
}
问题是它只能工作一次。 http://jsfiddle.net/zbh691y0/
最佳答案
始终使用 prop,而不是 attr 和 prop。
http://jsfiddle.net/zbh691y0/1/
$('.insurance-option-select').on('click', function () {
if ($(this).find('input').prop('checked')) {
$(this).find('input').prop('checked', false);
} else {
$(this).find('input').prop('checked', true);
}
});
这也可以通过执行以下操作来简化:
$('.insurance-option-select').on('click', function () {
cb = $(this).find('input')
cb.prop('checked', ! cb.prop('checked'))
});
属性checked
是一个 bool 值。因此,您可以使用 !
来否定它的值。想象一下这段代码:
cb = $(this).find('input')
is_checked = cb.prop('checked') // This will be true if it is checked, and false if not
inverse_is_checked = ! is_checked // This will be the opposite of is_checked
cb.prop('checked', inverse_is_checked) // Now you set the checked property value to the inverse of what it was originally
但这可以在一行中完成,如上所示。
关于javascript - jQuery 只工作一次? jsFiddle 已附,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25755332/