【问题标题】:dispatchEvent trigger not working on element iddispatchEvent 触发器不适用于元素 ID
【发布时间】:2018-07-21 16:35:11
【问题描述】:

我在为 addEventListener 事件调用 dispatchEvent 时遇到问题。代码完全符合我的要求,但不同之处在于我想在按钮 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" );

我尝试用“按钮 ID”替换 document,但它不起作用。

【问题讨论】:

标签: jquery dispatchevent


【解决方案1】:

这里需要进行一些小的更改,如下面的 cmets 中所述:

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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-17
    • 1970-01-01
    • 2020-04-24
    • 2014-05-14
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多