如何在 Jquery 中选中复选框时收听
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6878757/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to listen to when a checkbox is checked in Jquery
提问by Jordash
I need to know when any checkbox on the page is checked:
我需要知道页面上的任何复选框何时被选中:
e.g.
例如
<input type="checkbox">
I tried this in Jquery
我在 Jquery 中试过这个
$('input type=["checkbox"]').change(function(){
alert('changed');
});
But it didn't work, any ideas?
但它没有用,有什么想法吗?
回答by David says reinstate Monica
Use the change()
event, and the is()
test:
使用change()
事件和is()
测试:
$('input:checkbox').change(
function(){
if ($(this).is(':checked')) {
alert('checked');
}
});
I've updated the above, to the following, because of my silly reliance on jQuery (in the if
) when the DOM properties would be equally appropriate, and also cheaper to use. Also the selector has been changed, in order to allow it to be passed, in those browsers that support it, to the DOM's document.querySelectorAll()
method:
我已将上述内容更新为以下内容,因为我愚蠢地依赖 jQuery(在 中if
),而 DOM 属性同样适用,而且使用起来也更便宜。选择器也已更改,以允许在支持它的浏览器中将其传递给 DOM 的document.querySelectorAll()
方法:
$('input[type=checkbox]').change(
function(){
if (this.checked) {
alert('checked');
}
});
For the sake of completion, the same thing is also easily possible in plain JavaScript:
为了完成起见,同样的事情在普通 JavaScript 中也很容易实现:
var checkboxes = document.querySelectorAll('input[type=checkbox]'),
checkboxArray = Array.from( checkboxes );
function confirmCheck() {
if (this.checked) {
alert('checked');
}
}
checkboxArray.forEach(function(checkbox) {
checkbox.addEventListener('change', confirmCheck);
});
References:
参考:
- JavaScript:
- jQuery:
回答by Jasper
$('input:checkbox').live('change', function(){
if($(this).is(':checked')){
alert('checked');
} else {
alert('un-checked');
}
});
jsfiddle: http://jsfiddle.net/7Zg3x/1/
jsfiddle:http: //jsfiddle.net/7Zg3x/1/
回答by Shef
$('input:checkbox').change(function(){
if($(this).is(':checked')){
alert('Checked');
}
});
回答by ShankarSangoli
Try this
尝试这个
$('input:checkbox').change(function(){
if(this.checked)
alert('checked');
else
alert('not checked');
});
回答by Daniel
If you want to use .on this works
如果你想使用 .on 这个作品
jQuery('input[type=checkbox]').on('change', function() {
if (this.checked) {
console.log('checked');
}
});
回答by Rafay
$("input:checkbox").change(function(){
alert($(this).val());
});
here is the fiddle http://jsfiddle.net/SXph5/
回答by dotty
$("input[type='checkbox']").click(function(){
alert("checked");
});
Just a normal .click
will do.
只要正常.click
就行。