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

后端 未结 2 1071
盖世英雄少女心
盖世英雄少女心 2021-01-27 19:01


I am trying to understand why the change event in the following example is not triggered (I\'ll show exactly where).

I have a checkbox, lets call it \'mainCheckbox

2条回答
  •  抹茶落季
    2021-01-27 19:22

    In general, the events are only fired in response to user actions, not actions in code. Setting the checked property on a checkbox does not fire its change event; the user changing the checkbox's checked state does.

    This is also true for when you use code to set the value of an input, the selectedIndex (or value) of a select, etc.

    It's also true in relation to the submit events on form elements: Calling an HTMLFormElement's submit function will submit the form without triggering its submit event. But, if you use jQuery to submit the form (e.g., if you call submit on a jQuery object wrapped around an HTMLFormElement), it does trigger its submit event handlers. This is an unfortunate by-product of jQuery's API design.

    If you want to trigger an event, you can do that with jQuery's trigger function. So if it's appropriate, after setting checked, you could .trigger("change"). In general I advocate not generating synthetic predefined events like that (instead, just call whatever function you need to call, or use a synthetic custom event), but there are valid use cases.

提交回复
热议问题