問題:
I've recently run into a rather nasty bug, wherein the code was loading a <select>
dynamically via JavaScript.我最近遇到了一個非常討厭的錯誤,其中的代碼是通過JavaScript動態加載<select>
。 This dynamically loaded <select>
had a pre-selected value.動態加載的<select>
具有預先選擇的值。 In IE6, we already had code to fix the selected <option>
, because sometimes the <select>
's selectedIndex
value would be out of sync with the selected <option>
's index
attribute, as below:在IE6中,我們已經有代碼來修復選定的<option>
,因爲有時<select>
的selectedIndex
值可能與選定的<option>
的index
屬性不同步,如下所示:
field.selectedIndex = element.index;
However, this code wasn't working.但是,此代碼無法正常工作。 Even though the field's selectedIndex
was being set correctly, the wrong index would end up being selected.即使正確設置了字段的selectedIndex
,也將最終選擇錯誤的索引。 However, if I stuck an alert()
statement in at the right time, the correct option would be selected.但是,如果我在正確的時間插入了alert()
語句,則將選擇正確的選項。 Thinking this might be some sort of timing issue, I tried something random that I'd seen in code before:考慮到這可能是某種時序問題,我嘗試了一些以前在代碼中看到的隨機現象:
var wrapFn = (function() {
var myField = field;
var myElement = element;
return function() {
myField.selectedIndex = myElement.index;
}
})();
setTimeout(wrapFn, 0);
And this worked!這有效!
I've got a solution for my problem, but I'm uneasy that I don't know exactly why this fixes my problem.我已經爲我的問題找到了解決方案,但是我不知道自己到底爲什麼能解決我的問題,對此我感到不安。 Does anyone have an official explanation?有人有官方解釋嗎? What browser issue am I avoiding by calling my function "later" using setTimeout()
?通過使用setTimeout()
調用函數“稍後”可以避免出現什麼瀏覽器問題?
解決方案:
參考一: https://stackoom.com/question/3Gkd參考二: Why is setTimeout(fn, 0) sometimes useful?