jQuery 检测复选框状态变化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7919716/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 00:27:29  来源:igfitidea点击:

detect checkbox state change

jquery

提问by neelmeg

I want to detect if user checks or unchecks a check box within an iframe and set a flag like so. But it does not seem to work as expected. Any pointers on the error on the code?

我想检测用户是否选中或取消选中 iframe 中的复选框并设置像这样的标志。但它似乎没有按预期工作。关于代码错误的任何指示?

jQuery("#frameName").contents().find(":checkbox").bind('change', function(){        
            val = true;
            alert("changed");
    });

But I can detect if a checkbox is checked by using

但是我可以通过使用来检测复选框是否被选中

var val = jQuery("#frameName").contents().find(":checkbox").is(":checked");

I want to be able to detect any state change on a checkbox and set the flag.

我希望能够检测复选框上的任何状态更改并设置标志。

回答by Rob W

Use the checkedDOM property to check whether a checkbox is checked or not. The changeevent is always triggered on change, even if the checkbox gets unchecked.

使用checkedDOM 属性检查复选框是否被选中。该change事件总是在更改时触发,即使复选框未选中。

jQuery("#frameName").contents().find(":checkbox").bind('change', function(){        
        val = this.checked; //<---
        alert("changed");
});

回答by GregL

Bind to the click event, not change. Checkboxes work on click.

绑定到点击事件,而不是改变。复选框在点击时起作用。

EDIT: It appears in modern browsers that changing the state of a checkbox, whether via mouse or keyboard, triggers at least the clickandthe changeevents.

编辑:看来,在现代浏览器,改变一个复选框的状态,无论是通过鼠标或键盘,触发至少clickchange事件。

See a jsFiddle demoI built for proof. Using the keyboard also triggers some key-related events, in addition to clickand change.

请参阅我为证明而构建的jsFiddle 演示。除了click和之外,使用键盘还会触发一些与按键相关的事件change