问题描述:

I want to make my own javascript. Is there any possibility to create my own event just like as click, hover. I want a event that wil really work. Like creating a event that will fire when user clicks on cancel/delete button.

网友答案:

See https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent and https://davidwalsh.name/customevent

var myElement = document.querySelector('p');

myElement.addEventListener("userLogin", function(e) {
  console.info("Event is: ", e);
  console.info("Custom data is: ", e.detail);
});

var myEvent = new CustomEvent("userLogin", {
  detail: {
    username: "davidwalsh"
  }
});

// Trigger it!
myElement.dispatchEvent(myEvent);
<p>Custom Event Element</p>
网友答案:

Creating an event listener in JavaScript requires doing two things: (1) selecting an element to "bind" an listener to and (2) adding an event listener:

// add event listener to table
var el = document.getElementById("#myElement");
el.addEventListener("click", function() {
  alert('element clicked!');
});

This particular implementation will run the function when the element with the ID myElement is clicked.

Check out MDNs page on event listeners for more information.


As the question was regarding "custom" events, you can create custom JavaScript events in the following way.

var event = new Event('build');

// Listen for the event.
var el = document.getElementById("#myElement");
el.addEventListener('build', function (e) { ... }, false);

// Dispatch the event.
el.dispatchEvent(event);

You can read more about custom JS events here.

相关阅读:
Top