本文翻译自:Check/Uncheck checkbox with JavaScript (jQuery or Vanilla)?
如何使用JavaScript,jQuery或vanilla选中/取消选中复选框?
#1楼
参考:https://stackoom.com/question/YQtx/使用JavaScript-jQuery或Vanilla-选中-取消选中复选框
#2楼
We can checked a particulate checkbox as, 我们可以检查微粒复选框,
$('id of the checkbox')[0].checked = true
and uncheck by , 并取消选中,
$('id of the checkbox')[0].checked = false
#3楼
Important behaviour that has not yet been mentioned: 尚未提及的重要行为:
Programmatically setting the checked attribute, does not fire the change
event of the checkbox . 以编程方式设置checked属性,不会触发复选框的change
事件 。
See for yourself in this fiddle: 在这个小提琴中亲眼看看:
http://jsfiddle.net/fjaeger/L9z9t04p/4/ http://jsfiddle.net/fjaeger/L9z9t04p/4/
(Fiddle tested in Chrome 46, Firefox 41 and IE 11) (小提琴在Chrome 46,Firefox 41和IE 11中测试过)
The click()
method click()
方法
Some day you might find yourself writing code, which relies on the event being fired. 有一天,你可能会发现自己正在编写代码,这依赖于被触发的事件。 To make sure the event fires, call the click()
method of the checkbox element, like this: 要确保事件触发,请调用checkbox元素的click()
方法,如下所示:
document.getElementById('checkbox').click();
However, this toggles the checked status of the checkbox, instead of specifically setting it to true
or false
. 但是,这会切换复选框的已检查状态,而不是专门将其设置为true
或false
。 Remember that the change
event should only fire, when the checked attribute actually changes. 请记住,只有在checked属性实际更改时才会触发change
事件。
It also applies to the jQuery way: setting the attribute using prop
or attr
, does not fire the change
event. 它也适用于jQuery方式:使用prop
或attr
设置属性,不会触发change
事件。
Setting checked
to a specific value 将checked
设置为特定值
You could test the checked
attribute, before calling the click()
method. 在调用click()
方法之前,您可以测试checked
属性。 Example: 例:
function toggle(checked) {
var elm = document.getElementById('checkbox');
if (checked != elm.checked) {
elm.click();
}
}
Read more about the click method here: 在此处阅读有关click方法的更多信息:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click
#4楼
I would like to note, that setting the 'checked' attribute to a non-empty string leads to a checked box. 我想要注意的是,将'checked'属性设置为非空字符串会导致选中复选框。
So if you set the 'checked' attribute to "false" , the checkbox will be checked. 因此,如果您将“已检查”属性设置为“false” ,则会选中该复选框。 I had to set the value to the empty string, null or the boolean value false in order to make sure the checkbox was not checked. 我必须将值设置为空字符串, null或布尔值false ,以确保未选中复选框。
#5楼
<script type="text/javascript">
$(document).ready(function () {
$('.selecctall').click(function (event) {
if (this.checked) {
$('.checkbox1').each(function () {
this.checked = true;
});
} else {
$('.checkbox1').each(function () {
this.checked = false;
});
}
});
});
</script>
#6楼
Try This: 试试这个:
//Check
document.getElementById('checkbox').setAttribute('checked', 'checked');
//UnCheck
document.getElementById('chk').removeAttribute('checked');