[英]How to trigger a change event with a custom HTMLElement as the target?
我已經在一個事件偵聽registred section
,其嵌入各種下拉菜單HTML標記:
function dropdownChange(e) {
window.console.log("The event is detected");
if (e.target.tagName === "SELECT")
window.console.log("The event's target is a dropdown"); // Some jobs
else
window.console.log("The event's target is NOT a dropdown"); // Some jobs
}
document.getElementById("filterSection").addEventListener("change", dropdownChange);
它工作正常。
我想要做的是在我的頁面加載時觸發一次更改事件。 據我了解Mozilla文檔,我應該在我的DOM准備好后執行以下操作:
document.getElementById("periode").dispatchEvent(new Event("change"));
但事件不是觸發器(我無法進入我的控制台)。 我認為事件傳播會成功...
如果我執行:
document.getElementById("filterSection").dispatchEvent(new Event("change"));
該事件被很好地觸發,但目標不是好事。
我究竟做錯了什么?
下拉列表的HTML代碼:
<section id="filterSection">
<label>Période</label>
<select name="periode" id="periode">
<option value="2014-08">2014 Août</option>
<option value="2014-07">2014 Juillet</option>
<option value="2014-06">2014 Juin</option>
<option value="2014-05">2014 Mai</option>
<option value="2014-04">2014 Avril</option>
<option value="2014-03">2014 Mars</option>
<option value="2014-02">2014 Février</option>
<option value="2014-01">2014 Janvier</option>
<option value="2013-12">2013 Décembre</option>
<option value="2013-11">2013 Novembre</option>
<option value="2013-10">2013 Octobre</option>
<option value="2013-09">2013 Septembre</option>
<option value="2013-08">2013 Août</option>
<option value="2013-07">2013 Juillet</option>
<option value="2013-06">2013 Juin</option>
</select>
<!-- Other dropdowns...-->
</section>
我的主要瀏覽器目標是Firefox.17
我建議使用document.querySelector
而不是getById,因為它更可靠。
因此,請在下面更改添加/調度事件。
document.querySelector("#periode").addEventListener("change", dropdownChange);
document.querySelector("#periode").dispatchEvent(new Event("change"));
更新:要擁有父級,並讓所有孩子擁有相同的事件,請遵循以下代碼:
function dropdownChange(e) {
window.console.log("The event is detected");
if (e.target.tagName === "SELECT") window.console.log("The event's target is a dropdown");
else window.console.log("The event's target is NOT a dropdown");
}
//shiv, add a forEach to nodeList prototype to use forEach method on querySelectorAll lsit.
NodeList.prototype.forEach = Array.prototype.forEach;
var parent = document.querySelectorAll("#filter select");
parent.forEach(function(e){
e.addEventListener("change", dropdownChange);
});
document.querySelector("#filter select").dispatchEvent(new Event("change"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.