问题
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