Javascript 如果更改源不是来自 html,则不会触发事件?

Javascript event not triggered if the change origin is not from the html?

我试图理解为什么未触发以下示例中的更改事件(我将显示具体位置)。

我有一个复选框,我们称它为 'mainCheckbox',选中时 - 我想选中其他一些相关的复选框(目前有效)。

此外,当我取消选中一个相关的复选框(子复选框)时 - 我想取消选中 mainCheckbox,这也有效 - 但这是我无法理解的地方:

我正在更改 mainCheckbox 的选中 属性(在 'childCheckbox' 的 onchange 处理程序中),

为什么没有调用 mainCheckbox 的 onchange 处理程序?
或者怎么没有触发主复选框的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.
        
    }
    
})

一般来说,事件仅在响应 用户 操作时触发,而不是代码中的操作。在复选框上设置 checked 属性 不会触发其 change 事件; 用户 更改复选框的选中状态。

当您使用代码设置 inputvalue、[=16= 的 selectedIndex(或 value)时也是如此], 等等

对于 form 元素上的 submit 事件也是如此:调用 HTMLFormElementsubmit 函数将提交表单而不触发其 submit 事件。 但是,如果您使用 jQuery 提交表单(例如,如果您调用 submit 包裹在 [=19= 的 jQuery 对象上]),它 触发它的 submit 事件处理程序。这是 jQuery 的 API 设计的不幸副产品。

如果你想触发一个事件,你可以用jQuery的trigger函数来实现。所以如果合适的话,在设置​​checked之后,你可以.trigger("change")。总的来说,我提倡不要 生成这样的合成预定义事件(相反,只需调用您需要调用的任何函数,或使用合成自定义事件),但有有效的用例。

当元素失去焦点时会触发 onchange 事件。由于您正在以编程方式更改值,因此您正在更改的元素永远不会失去焦点。您可能希望查看 oninput 事件。