[英]Is it possible to listen for selectedIndex change?
當通過簡單分配(如myElement.selectedIndex=1
)完成更改時,我正在尋找一種方法(或解決方法)來訂閱selectedIndex
更改(在<select>
元素上)。
<select id = "mySelect" onchange="myListener()">
<option>0</option>
<option>1</option>
</select>
<script>
function myListener() {
console.log('Yes, I hear...'); // doesn't work on selectedIndex assignment
}
document.getElementById('mySelect').selectedIndex = 1;
</script>
似乎不可能,但也許有一些解決方法。
dispatchEvent
不是一個選項(偵聽器附件必須從外部完成)。
也許不是最好的答案,但你確實提到了解決方法..
您可以嘗試覆蓋您嘗試檢測更改的 object 的設置器。
let mySelect = document.getElementById("mySelect"); const callback = () => { console.log("Yes, I hear..."); }; const original = Object.getOwnPropertyDescriptor( Object.getPrototypeOf(mySelect), "selectedIndex" ); Object.defineProperty(mySelect, "selectedIndex", { set: function (t) { callback(); return original.set.apply(this, arguments); }, get: function () { return original.get.apply(this); } }); let myButton = document.getElementById("myButton"); myButton.addEventListener("click", () => { mySelect.selectedIndex = 1; });
<select id="mySelect"> <option>0</option> <option id="option1">1</option> </select> <button id="myButton"> change selector value to 1 </button>
值得一提的是,在此處手動更改 select 時,回調不會運行。如果您想保留該行為,可以添加一個像往常一樣調用callback
的事件偵聽器,盡管可能存在一個更好的解決方案來捕獲這兩種情況。
我的回答有點晚了。 您可以使用select.dispatchEvent(new Event('change'));
.
function myListener() { console.log('Yes, I hear...'); // doesn't work on selectedIndex assignment } select = document.getElementById('mySelect'); select.dispatchEvent(new Event('change'));
<select id = "mySelect" onchange="myListener()"> <option>0</option> <option>1</option> </select>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.