开发者

transfer event from one dom to other dom in javascript

开发者 https://www.devze.com 2022-12-25 18:59 出处:网络
In javascript, let say I got two nodes(node A, 开发者_StackOverflow中文版node B). when I click on node A, can I transfer \"click\" event to node B, so event handler for node B will execute.Triggering

In javascript, let say I got two nodes(node A, 开发者_StackOverflow中文版node B). when I click on node A, can I transfer "click" event to node B, so event handler for node B will execute.


Triggering a click event is fairly easy on buttons and other input elements, they have a click() method:

elementA.onclick = function () { elementB.click(); }

It's slightly more complicated with other events or elements that don't support the click method, you need to trigger the event using fireEvent or dispatchEvent, depending on the browser:

elementA.onclick = function () {
    var elementB = document.getElementById("elementB");
    if ("dispatchEvent" in elementB) {
        var evt = document.createEvent("MouseEvents");
        evt.initMouseEvent("click", true, true, window,
            0, 0, 0, 0, 0, false, false, false, false, 0, null);
        elementB.dispatchEvent(evt);
    }
    else if ("fireEvent" in elementB)
        elementB.fireEvent("onclick");
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号