问题
I am facing an issue while calling dispatchEvent
for addEventListener
event. The code is doing exactly what I want, but the difference is that I want to call dispatchEvent
on the button id rather than document
.
function fire( elem, type ) {
var evt = elem.createEvent("Events");
evt.initEvent( type, true, true, window, 1);
elem.dispatchEvent(evt);
}
document.addEventListener( "click", function() {
console.log( "Fired a synthetic click event" );
}, false );
fire( document, "click" );
I tried replacing document
with "button id" but it's not working.
回答1:
Several small changes were necessary here, described in the comments below:
function fire(elem, type) {
console.log("Dispatching a synthetic event");
// .createEvent() is a document function:
var evt = document.createEvent("Events");
evt.initEvent(type, true, true, window, 1);
// ...but you want to dispatch it on the element:
elem.dispatchEvent(evt);
}
// The event listener belongs on the element, not the document (unless you want the click event to fire whenever the user clicks anywhere on the page):
document.getElementById("theID").addEventListener("click", function() {
console.log("Fired a click event");
}, false);
// The fire() function expects a DOM element, not just its ID:
fire(document.getElementById("theID"), "click");
<button id="theID">Hello</button>
来源:https://stackoverflow.com/questions/51458104/dispatchevent-trigger-not-working-on-element-id