jQuery复选框勾选状态改变事件 [英] jQuery checkbox checked state changed event
问题描述
$('。checkbox')我想要一个事件触发客户端, .click(function(){
if($(this).is(':checked')){
// Do stuff
}
});
基本上,我想让它发生在页面上的每个复选框。这个方法是点击点击并检查状态吗?
我在想,一定要有一个更干净的jQuery方式。任何人都知道解决方案?
绑定到更改
事件而不是点击
。但是,您可能仍然需要检查该复选框是否被选中:
$(。checkbox)。 (function(){
if(this.checked){
// Do stuff
}
});
绑定到 在评论中修改 更改的主要优点
事件code 更改事件。
另请注意,我使用了 this.checked
而不是将元素包装在一个jQuery对象中,并使用jQuery方法,只是因为直接访问DOM元素的属性越来越短。
编辑(见注释)
要获取所有复选框,您有几个选项。您可以使用 :checkbox
伪-selector:
$(:checkbox)
或者您可以使用属性等于< a> selector:
$(input [type ='checkbox'])
I want an event to fire client side when a checkbox is checked / unchecked:
$('.checkbox').click(function() {
if ($(this).is(':checked')) {
// Do stuff
}
});
Basically I want it to happen for every checkbox on the page. Is this method of firing on the click and checking the state ok?
I'm thinking there must be a cleaner jQuery way. Anyone know a solution?
Bind to the change
event instead of click
. However, you will probably still need to check whether or not the checkbox is checked:
$(".checkbox").change(function() {
if(this.checked) {
//Do stuff
}
});
The main benefit of binding to the Redacted in commentschange
event over the click
event is that not all clicks on a checkbox will cause it to change state. If you only want to capture events that cause the checkbox to change state, you want the aptly-named change
event.
Also note that I've used this.checked
instead of wrapping the element in a jQuery object and using jQuery methods, simply because it's shorter and faster to access the property of the DOM element directly.
Edit (see comments)
To get all checkboxes you have a couple of options. You can use the :checkbox
pseudo-selector:
$(":checkbox")
Or you could use an attribute equals selector:
$("input[type='checkbox']")
这篇关于jQuery复选框勾选状态改变事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!