jQuery 复选框选中状态更改事件 [英] jQuery checkbox checked state changed event

查看:23
本文介绍了jQuery 复选框选中状态更改事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这篇关于jQuery 复选框选中状态更改事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆