dispatchEvent触发器不适用于元素ID

时间:2018-07-21 16:35:11

标签: jquery dispatchevent

调用dispatchEvent事件的addEventListener时遇到问题。该代码完全可以实现我想要的功能,但是区别在于我想在按钮id上调用dispatchEvent而不是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" );

我尝试将document替换为“按钮ID”,但无法正常工作。

1 个答案:

答案 0 :(得分:0)

此处需要进行一些小的更改,如以下评论所述:

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>