简体   繁体   中英

How to check if an event was fired or not?

I'm using Chrome DevTools to debug JavaScript. In my script I bound a click event to an element using the jQuery bind() method. How to check if that event was fired or not?

Edit
Sorry because I wasn't so specific, I know that I can use console.log() or set a breakpoint inside the event listener body. What I'm talking about here is an out of box feature of the Chrome DevTools that allows you to check that without using the console, eg a tab that contains all the events that were fired with related information.

Regarding Chrome, checkout the monitorEvents() via the command line API.

  • Open the console via Menu > Tools > JavaScript Console.
  • Enter monitorEvents(window);
  • View the console flooded with events

     ... mousemove MouseEvent {dataTransfer: ...} mouseout MouseEvent {dataTransfer: ...} mouseover MouseEvent {dataTransfer: ...} change Event {clipboardData: ...} ... 

There are other examples in the documentation . I'm guessing this feature was added after the previous answer.

Use console.log() for more user friendly check (console must be opened of course to see the result):

$("#myElement").bind("click", function() {
   console.log("Fired!");
});

Or you can alert it, which is much more anoying tho:

$("#myElement").bind("click", function() {
   alert("Fired!");
});

You can try below code to check if event fire or not.

var eventFire = false;

$("button").on("click", function() {
   eventFire = true;
if(eventFire){
    alert('Event Fired')
}   
});   

I normally use an alert (because we develop on Rails -- console is unreliable):

$(document).on("event", "#element", function() { 
    alert("event");
});

The bottom line is you're going to have to trigger some "visible" thing to see if the event fired. If it doesn't, you'll either not be binding to the correct element, or your event won't be firing

Hope this helps!

Using jQuery Try the following:

$("#el").on("click", function() {
    console.log("Fired!");
});

You can then see if the event was fired or not. So basically Just add a log in your function of where the event is triggering should do the trick.

You can put an "alert('message');" in your event handler and see a popup each time the handler fires. Or you can put a "console.log('message');" in your event handler and review the log to see all the times that the event fired. Or you can put "debugger" in your event handler and step through your code as it executes in the chrome debugger. There is also a way to dynamically find an event handler and insert a debugger break point in your code using the chrome dev tools elements panel.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM