dispatchEvent trigger not working on element id

我只是一个虾纸丫 提交于 2019-12-24 19:53:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!