如何可靠地检测复选框何时被检查,无论如何?

mik*_*kel 6 javascript jquery event-handling javascript-events

我正在寻找一种方法来检测复选框选中的值何时被更改.addEventListener()或jQuery on()主要工作,但都不会检测到这样做的变化:

<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>
Run Code Online (Sandbox Code Playgroud)

有没有办法可以发现这种变化?即使只适用于最新浏览器的东西也会很棒.

编辑:要清楚,我想检测页面上任何脚本所做的更改.我不一定控制它们,所以我不能自己触发事件.

Tim*_*own 5

对于它的价值(我想说,不多),您可以在 IE 中仅使用其专有propertychange事件来执行此操作。在其他浏览器中,我很确定您现在唯一的选择是轮询。

演示: http: //jsfiddle.net/X4a2N/1/

代码:

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

  • @JanDvorak:不,你不能,正如我所解释的。没有属性改变,并且 MutationObservers 不观察属性。 (3认同)