[英]Javascript's "selectedIndex" appears to work, but actually doesn't give the same behavior as a real click
我有一個 HTML 表單,其中包含來自 W3Schools 的 Javascript 自定義下拉功能。 它用一個非常簡潔的下拉菜單替換了丑陋的默認下拉菜單,並且在大多數情況下都有效。 但是,我遇到了一個問題。
自定義下拉代碼使用“selectedIndex”函數來定義用戶單擊時應選擇哪個標簽。 它似乎有效,但我也在使用 Sisyphus 的“保存表單數據”插件,當我刷新頁面時,用戶更改丟失了。
我知道這不是 Sisyphus 或我的實現的問題,因為如果我取消隱藏默認的原始下拉列表,我點擊它,刷新后選項保存得很好。
此查詢顯示“selectedIndex”函數給出的結果與用戶實際單擊標簽時的結果不完全相同。 它似乎改變了價值,但不知何故並沒有真正注冊它,令人毛骨悚然....
在stackoverflow上閱讀了類似的問題后,我在“selectIndex”函數下添加了以下兩行:嘗試以編程方式將其“selected”狀態設置為“true”,並觸發點擊:
s.selectedIndex = i;
s.options[i].selected = true;
s.options[i].click();
仍然沒有運氣。 這是代碼的更廣泛視圖:
// When an item is clicked, update the original select box, and the selected item
for (i = 0; i < sl; i++) {
if (s.options[i].innerHTML == this.innerHTML) {
//update the original select box
s.selectedIndex = i;
s.options[i].selected = true;
s.options[i].click();
//update the new select box
h.innerHTML = this.innerHTML;
}
}
這是 HTML:
<div class="dropdown has-label">
<label for="jours_entiers_de_travail">Number of days</label>
<div class="select-wrapper">
<select name="jours_entiers_de_travail" id="jours_entiers_de_travail">
<option value="1">1 day</option>
<option value="2">2 days</option>
<option value="3">3 days</option>
</select>
</div>
</div>
在這個 Codepen 上可以看到下拉菜單的完整版本:
https://codepen.io/benviatte/pen/OJNYwRy
這個 codepen 似乎有效,但是當我嘗試使用 selectedIndex 分配的值時,問題又出現了,例如 Sisyphus。 該值似乎沒有正確分配。
非常感謝您的幫助
Sisyphus 文檔暗示它使用change
事件來監視表單元素的更新。 源代碼似乎在bindSaveDataOnChange
函數的 JSDoc 標記中確認了這一點。
因此,嘗試在選擇框上觸發更改事件,而不是以編程方式單擊選項元素。 未經測試但可能喜歡
//update the original select box
s.selectedIndex = i;
s.options[i].selected = true;
// s.options[i].click(); // replace with:
$(s).trigger("change"); // trigger change event on select box
另請參閱使用 jquery 觸發更改事件 <select> 以了解在 jQuery 和普通 JavaScript 中觸發更改事件的各種方法,以及trigger() | jQuery API 文檔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.