简体   繁体   中英

How can I preventDefault inside a callback inside an event handler?

For example I have something like

$('div').on('click', '.button', function(event){
  $('.showdiv').show('fast', function(){
     var myvar = someFunction();
     if(myvar == 1){
        event.preventDefault();
     }
  });
});

I want to prevent the Default behaviour of the click button inside the callback of the show function (to ensure that the show div is shown before runnin the myvar function). IBut I can't make the preventDefault() works. How can I make it happen? Thanks!

Please check below updates code, I think you need also need to define event in show function.

$('div').on('click', '.button', function(event){
      $('.showdiv').show('fast', function(event){
         var myvar = someFunction();
         if(myvar == 1){
            event.preventDefault();
         }
      });
    });

Hope this will work for you.

It should not be inside the callback.

If you put it inside the callback the default behavior would have been already fired :

$('div').on('click', '.button', function(event)
  event.preventDefault();{
  $('.showdiv').show('fast', function(){
     var myvar = someFunction();
     if(myvar == 1){
     }
  });
});

in the code you are not passing event as parameter. change to

 $('.showdiv').show('fast', function(){
 var myvar = someFunction(event); // pass parameter
 if(myvar == 1){
    event.stopPropagation();
    event.preventDefault();
 }
});

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