简体   繁体   中英

jQuery: Prevent bound js from running on click, then running it if condition is met

Sorry for the weird title, I couldn't think of a better way to word it.

The situation is: I have a link that is generated by a complex system (can't be changed), which fires a JS function when clicked.

Instead, when the link is clicked I want a modal box to appear asking the user if they are sure. If they choose yes then the original JS function will run. If not then the modal closes and nothing happens.

Is it possible to unbind, capture, and rebind the original function like this?

Pseudo-code would be as follows, hopefully it's possible:

$('a.link').click(function(){

    // *** Capture original JS function bound to link ***

    // *** var agree = Run new function (open modal box) ***

    if(agree === true){

       // *** Run original function ***

    }else{

       // *** Close modal box *** 

    }
});

I'm probably thinking about this the wrong way, if there is a better one please let me know!

Your event handlers are going to fire in the order they are attached. If you can insert yourself in the first position of the queue , then on the callback parameter you can call e.stopImmediatePropagation(). It will prevent other events from firing. Set a variable record the response, and trigger a click on the link again.

var check = null; //store user's response

$(".preventable").on("click", function(e) {
  if(check == null) {
    e.stopImmediatePropagation();
    alert("hijacked")

    check = true; //confirm here

    if(check)
        $('.preventable').click();
  }
}

$(".preventable").on("click", function(e) { alert("clicked2"); })

jsfiddle

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