How to reliabily detect when a checkbox has been checked, no matter how?

半城伤御伤魂 提交于 2019-12-10 13:37:56

问题


I'm looking for a way to detect when a checkbox checked value has been changed. addEventListener() or jQuery on() mostly work, but neither will detect a change made this way:

<input type="checkbox" id="testCheckbox">

<!--- some other script further down the page, not under my control -->
<script type="text/javascript">
   document.getElementById("testCheckbox").checked = true;
</script>

Is there a way I can detect this change ? Even something that only works in the latest browsers would be great.

Edit: To be clear, I want to detect changes made by any script on the page. I don't necessarily control them, so I can't trigger an event myself.


回答1:


For what it's worth (not much, I'd say), you can do this in IE only using its proprietary propertychange event. In other browsers, I'm pretty certain your only option for now is polling.

Demo: http://jsfiddle.net/X4a2N/1/

Code:

document.getElementById("testCheckbox").onpropertychange = function(evt) {
    evt = evt || window.event;
    if (evt.propertyName == "checked") {
        alert("Checkedness changed!");
    }
};



回答2:


I don't think there is an elegant way. There is an Object.observe proposal for future versions of Javascript.

For now you should trigger the change event as undefined suggested. You could also define a setter function that sets the value and triggers change for you.




回答3:


This is not possible. You must fire the Change event manually.

    Actions that invoke the CheckboxStateChange event:
          1. Changing the state of the checkbox by a mouse click.
          2. Changing the state of the checkbox with an accesskey.
          3. Changing the state of the checkbox with the SPACE key.

    Actions that do not invoke the CheckboxStateChange event:
          1. Changing the value of the checked property from script.



回答4:


At the moment there's still no way to do this without polling or using a shadow DOM framework like React that monitors state. This is because checkbox/radio .checked = true property change is a state change, not a DOM mutation. Here's a demo of this:

http://jsfiddle.net/6DHXs/1/



来源:https://stackoverflow.com/questions/14500747/how-to-reliabily-detect-when-a-checkbox-has-been-checked-no-matter-how

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!