简体   繁体   中英

jQuery, only trigger event, if no other event was triggered

Is there a way, to find out, if a jquery event was already caught by another event-listener?

The following example: I have the following event bindings:

$("body").on("click", ".linkarea", function (e) {
    document.location.href = $(this).find("a")a.attr("href");
});
$("body").on("click", ".delete", function (e) {
    console.log("DELETE");
});

This is how my HTML look like:

<div class="linkarea">
    <h1><a href="/test.html">LINKED</a></h1>
    <p>Blabla</p>   
    <a class="btn delete">DELETE</a>
</div>

What I want to achieve is, that if an user clicks on any part of the div (except the .delete button), he should be redirected to /test.html. If he clicks on .delete button, only(!) the other event code should be executed.

I know, that I could add "e.stopPropagation()" to the delete-event, but maybe I use the .delete class on another place, and there it could be necessary, that it bubbles. What I am looking for is something like this:

$("body").on("click", ".linkarea", function (e) {
    if(!e.wasAlreadyExecuted)
        document.location.href = $(this).find("a")a.attr("href");
});

You could filter it out regarding event.target :

$("body").on("click", ".linkarea", function (e) {
    if($(e.target).closest('.delete').length) return;
    document.location.href = $(this).find("a")a.attr("href");
});

EDIT:

I know, that I could add "e.stopPropagation()" to the delete-event, but maybe I use the .delete class on another place, and there it could be necessary, that it bubbles.

Or stop event propagation from .delete click handler:

 
 
 
  
  $("body").on("click", ".delete", function (e) { console.log("DELETE"); e.stopPropagation(); });
 
  

You could try to check the event current target :

$("body").on("click", ".linkarea", function (event) {
   if(event.currentTarget.className.match(/delete/)){
         //your stuff
   }else{
          //your other stuff
   }
});

Just be aware that it won't work on IE8-

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