【问题标题】:Why does not onChange event produced?为什么不产生 onChange 事件?
【发布时间】:2012-06-08 22:46:45
【问题描述】:

假设,我们有以下标记:

<form>
    <button type="button" id="all">check all</button>
    <button type="button" id="none">check none</button>
    <input type="checkbox" value="one" />
    <input type="checkbox" value="two" />
    <input type="checkbox" value="three" />
</form>

以下 JavaScript 代码:

(function($, document) {
    $('#all').on('click', function() {
         $('input', $(this).parent()).prop('checked', 'checked');
    });
    $('#none').on('click', function() {
        $('input', $(this).parent()).removeProp('checked');
    });

    $('input').on('change', function() {
        alert(this.value);
    });
}(jQuery, document));

(见http://jsfiddle.net/inst/h7kyq/1/

为什么当我们点击任意一个按钮时,input 的 onChange 事件处理程序没有执行?

【问题讨论】:

  • 在布尔属性上使用.prop() 时,使用布尔值。 .prop('checked', true).prop('checked', false)
  • 请勿使用 removeProp() 除非您想永久删除该属性,因为您无法再次使用/将该属性添加到元素中。阅读api.jquery.com/removeProp 正如您在您的小提琴中所说的,一旦您单击删除所有选择不再起作用。

标签: javascript jquery html events checkbox


【解决方案1】:

对输入元素的任何编程更改(从脚本更改)都不会触发onchange 事件。

或者,您应该在更改状态/值时手动触发更改事件。

见下文,

$('input', $(this).parent()).removeProp('checked').change();

演示: http://jsfiddle.net/h7kyq/4/

【讨论】:

    【解决方案2】:

    在 javascript 中发生更改时不会触发事件。您需要自己触发事件:

    $('input', $(this).parent()).removeProp('checked').change();
    

    【讨论】:

    • 这是故意行为。代码更改时不会触发事件,因为它可能会无意中触发我们宁愿不运行的代码,除非用户是进行更改的人。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-03
    • 2019-07-19
    • 1970-01-01
    • 1970-01-01
    • 2012-10-13
    相关资源
    最近更新 更多