jQuery 复选框选中状态更改事件

2022-01-15 00:00:00 event-handling jquery javascript

我希望在选中/取消选中复选框时触发客户端的事件:

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?

我认为必须有一个更干净的 jQuery 方式.有人知道解决办法吗?

I'm thinking there must be a cleaner jQuery way. Anyone know a solution?

推荐答案

绑定到 change 事件而不是 click.但是,您可能仍需要检查复选框是否被选中:

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
    }
});

click 事件相比,绑定到 change 事件的主要好处是,并非所有对复选框的点击都会导致它改变状态.如果您只想捕获导致复选框更改状态的事件,则需要恰当命名的 change 事件. 在评论中编辑

The main benefit of binding to the change 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. Redacted in comments

还要注意,我使用 this.checked 而不是将元素包装在 jQuery 对象中并使用 jQuery 方法,仅仅是因为直接访问 DOM 元素的属性更短、更快.

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.

编辑(见评论)

要获得所有复选框,您有几个选项.您可以使用 :checkbox 伪选择器:

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']")

相关文章