簡體   English   中英

如何可靠地檢測復選框何時被檢查,無論如何?

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

我正在尋找一種方法來檢測復選框選中的值何時被更改。 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>

有沒有辦法可以發現這種變化? 即使只適用於最新瀏覽器的東西也會很棒。

編輯:要清楚,我想檢測頁面上任何腳本所做的更改。 我不一定控制它們,所以我不能自己觸發事件。

我不認為有一種優雅的方式。 有針對未來Javascript版本的Object.observe提議。

現在,您應該以未定義的建議觸發更改事件。 您還可以定義一個setter函數,用於設置值並為您觸發change

對於它的價值(不多,我會說),你只能使用其專有的propertychange事件在IE中執行此操作。 在其他瀏覽器中,我很確定你現在唯一的選擇是輪詢。

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

碼:

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

這是不可能的。 您必須手動觸發Change事件。

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.

目前,如果沒有輪詢或使用像React監視狀態的影子DOM框架,仍然無法做到這一點。 這是因為checkbox / radio .checked = true屬性更改是狀態更改,而不是DOM突變。 這是一個演示:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM