Javascript 复选框更改事件未触发

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

Checkbox change event not firing

javascriptjquery

提问by user356247

This is my code:

这是我的代码:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js"></script>
<script>
  $(document).ready(function() {
    $('.chk').live('change', function() {
      alert('change event fired');
    });
    $('a').click(function() {
      $('.chk').attr('checked', true);
    });
  });
</script>
</head>
<body>
<div class="chkHolder">
  <input type="checkbox" class="chk" name="a" id="a" />
  <input type="checkbox" class="chk" name="b" id="b" />
</div>
<a href="#">check all</a>
</body>
</html>

When I click on the "check all" hyperlink, I want the change event fired for each of the checkboxes. However, that is not happening.

当我单击“全选”超链接时,我希望为每个复选框触发更改事件。然而,这并没有发生。

Any ideas?

有任何想法吗?

Many thanks!

非常感谢!

回答by Samich

use: $('.chk').attr('checked', true).change();

用: $('.chk').attr('checked', true).change();

Live example: http://jsfiddle.net/NRPSA/1/

现场示例:http: //jsfiddle.net/NRPSA/1/

回答by jeffreydev

When you change the attribute also use the following:

当您更改属性时,还使用以下内容:

$('.chk').trigger('change');

Or in your code like other people have suggested:

或者像其他人建议的那样在您的代码中:

$('.chk').attr('checked', true).trigger('change');

回答by ipr101

Try changing

尝试改变

$('a').click(function() {
      $('.chk').attr('checked', true);
});

To -

到 -

$('a').click(function() {
      $('.chk').attr('checked', true).trigger('change');
 });

That should force a trigger of the 'change' event.

这应该会强制触发“更改”事件。

Working demo - http://jsfiddle.net/ipr101/pwmBE/

工作演示 - http://jsfiddle.net/ipr101/pwmBE/

回答by Shree

try this.

尝试这个。

<div id ="chkall"> <a href="#">check all</a> <div>

            $('#chkall a').live("change", function() {
            $('.chk').attr('checked', true);
            });