使用 jQuery 更改 .prop 不会触发 .change 事件

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

Changing .prop using jQuery does not trigger .change event

jquery

提问by fuzzybabybunny

I've got an event listener on a checkbox:

我在复选框上有一个事件侦听器:

<input type="checkbox" name="something">

My event listener:

我的事件监听器:

$('input[type="checkbox"][name="something"]').change(function() { 
    //DO SOMETHING 
});

I have another event listener that changes .propof the checkbox:

我有另一个更改.prop复选框的事件侦听器:

$('#button').click(function() { 
    $('input[type="checkbox"][name="something"]').prop("checked", false);
});

When I check the checkbox DO SOMETHINGtriggers. When I click on the #button, the .propchanges and I see the checkbox visually uncheck, but DO SOMETHINGdoesn't get triggered...

当我选中复选框时DO SOMETHING会触发。当我单击 时#button.prop更改并且我看到复选框在视觉上取消选中,但DO SOMETHING没有被触发...

Something I'm overlooking?

我忽略了什么?

回答by Milind Anantwar

Change event is fired when the value is changed by users interaction on page and not when value is modified using code.

当页面上的用户交互更改值而不是使用代码修改值时,会触发更改事件。

Here you need to use .change()or .trigger("change")after changing the property:

这里需要使用.change().trigger("change")更改属性后:

$('input[type="checkbox"][name="something"]').prop("checked", false).change();

Working Demo

工作演示