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");
}
精彩评论