我试图理解为什么以下示例中的更改事件没有被触发(我将准确显示在哪里)。
我有一个复选框,我们将其称为“主复选框”,选中时 - 我想检查一些其他相关的复选框(到目前为止有效)。
此外,当我取消选中相关复选框之一(子复选框)时 - 我想取消选中 mainCheckbox,这也有效 - 但这里有一些我无法理解的内容:
我正在更改 mainCheckbox 的选中属性(在onchange
“childCheckbox”的处理程序),
怎么来的onchange
mainCheckbox 的处理程序没有被调用?
或者说怎么会出现onchange
主复选框的事件未触发?
这是代码:
//binding to the 'mainCheckbox' change event:
$("[data-role='group']").bind("change", function(event){
//checking / unchecking all related checkboxes respectivly
$("li input[data-group='" + event.target.id + "'").prop('checked', $(this).prop("checked"));
})
//binding to the change event of every 'child checkbox'
$("li input[data-group]").bind("change", function(){
if (event.target.checked){
//if the child checkbox is now checked - I am checking if now all child checkboxes are checked,
//if so - I need to check the main checkbox.
if ($("[data-group=" + event.target.dataset.group + "]:checked").length == $("[data-group=" + event.target.dataset.group + "]").length){
$("#" + event.target.dataset.group).prop("checked", true);
}
//TODO: add this device to the selectedDevices array.
}
else {
//the checkbox is now unchecked - so I am unchecking the main checkbox -
//but here is my failing to understand part: I am unchecking the main checkbox -
//why the change event is not triggered? I thought that now all child checkboxes will be unchecked as well
//(I am happy they are not :) just failing to understand why)...
$("#" + event.target.dataset.group).prop("checked", false);
//TODO: remove this device from the selectedDevices array.
}
})
一般来说,事件仅在响应时触发user动作,而不是代码中的动作。设置checked
复选框上的属性不会触发其change
事件;这user更改复选框的选中状态即可。
当您使用代码设置value
of an input
, the selectedIndex
(or value
) of a select
, etc.
对于以下方面来说也是如此submit
事件于form
元素: 调用HTMLFormElement
's submit
函数将提交表单而不触发其submit
event. But,如果您使用 jQuery 提交表单(例如,如果您调用submit
围绕一个 jQuery 对象HTMLFormElement
), it does触发其submit
事件处理程序。这是 jQuery API 设计的一个不幸的副产品。
如果你想触发一个事件,你可以使用 jQuery 来做到这一点trigger http://api.jquery.com/trigger功能。所以如果合适的话,设置后checked
, 你可以.trigger("change")
。总的来说我主张not生成类似的合成预定义事件(相反,只需调用您需要调用的任何函数,或使用合成自定义事件),但有有效的用例。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)