简体   繁体   中英

Jquery .on('click,'button' not working

I need to check if user closed browser. There is no reliable way, but the most accurate way seems to use onbeforeunload and check if a link or a button was clicked. I will also add f5 and some other extra checking.

But I have problem with button. If I click button, ajax call will be made even if there is if(window.link_was_clicked==false) condition.

<button onclick="setLocation('http://dev.site.com/checkout/')" class="button" title="Checkout" type="button"><span><span>Checkout</span></span></button>

And script:

jQuery(document).on('click', 'button', function(event) {
  window.link_was_clicked= true;
});  

window.onbeforeunload = function() {
  if(window.link_was_clicked==false){                
    //make ajax call      
  }
};

It seems the problem is because there is setLocation function attached to button onclick . Is there any way to trigger jQuery(document).on first?

That variable doesnt exist on before load. so add it on the top and try again

     window.link_was_clicked=window.link_was_clicked||false;
     jQuery(document).on('click', 'button', function(event) {
         window.link_was_clicked= true;
      });  

     window.onbeforeunload = function() {
         if(window.link_was_clicked==false){                
        //make ajax call      
     }
    };

Since you haven't provided the code for setLocation() , I'll assume that that's where the problem is. Now, regarding a change to the order of execution of your click event handlers:

It is in general bad to have both embedded onclick and jquery-bound handlers, it leads to all sorts of confusion. If you can't change the html, however, you could do what this guy suggests: https://stackoverflow.com/a/7507888/2685386

$(document).ready(function() {
    var myClick = $('button').attr('onclick');
    $('button').removeAttr('onclick');

    $(document).on('click', 'button', function(e) {
        window.link_was_clicked=true;
        // do my other stuff here....
        eval(myClick);// this will now call setLocation()
    });
});

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