如何用自定义HTMLElement作为目标来触发一个更改事件

How to trigger a change event with a custom HTMLElement as the target?

本文关键字:一个 事件 HTMLElement 自定义 何用 目标      更新时间:2023-09-26

我在section HTML标签上注册了一个eventlistener,其中嵌入了各种下拉菜单:

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"));

UPDATE:有一个父节点,并让所有子节点有相同的事件,代码如下:

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"));
http://jsfiddle.net/Holybreath/5sda7zsc/6/