Is it possible to re-create a “onClick event” using custom events in javascript?

痴心易碎 提交于 2020-01-06 22:00:50

问题


I'm trying to learn about custom events and I got curious. Could you create the onClick event verbatim but written in a Custom Event?

ex. create an element:

<h1 id="clicky">click here</h1>

Create a custom event that is the same as click event?

obj = document.getElementById('clicky');

obj.addEventListener("fakeClick", function(e) { console.log(e.detail) });


var event = new CustomEvent("fakeClick", {
  detail: {
    hazcheeseburger: true
  }
});

obj.dispatchEvent(event);

Heres a JSFiddle


回答1:


it depends on what you mean by making it 'the same as click event'. Custom event fire to the corresponding Dom element when you call dispatchEvent (like what u did above). So basically if u dispatch the custom event within a click event handler, then it basically simulate a click event, but there seems not much reason for doing so.

p.s. The error u got from fiddle is because u haven't defined the function process that u called in the fakeClick event handler

========== more details =========

What I meant was you can use custom event in the following way to 'simulate' click event, but that really doesn't serve the purpose since you can just directly use the browser click event.

var event = new CustomEvent("fakeClick", {
  detail: {
    hazcheeseburger: true
  }
});

obj = document.getElementById('clicky');

obj.addEventListener("click", function () {
    this.dispatchEvent(event);
});

obj.addEventListener("fakeClick", function(e) { console.log(e.detail) });


来源:https://stackoverflow.com/questions/33989046/is-it-possible-to-re-create-a-onclick-event-using-custom-events-in-javascript

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