Is it possible to re-create a “onClick event” usin

2019-08-26 02:12发布

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条回答
孤傲高冷的网名
2楼-- · 2019-08-26 02:33

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) });
查看更多
登录 后发表回答