开发者

jQuery unload alert only when an id is not present

开发者 https://www.devze.com 2023-04-11 05:17 出处:网络
I\'m working on a shopping cart page and I\'d like an alert to be displayed when the user tries to leave the page when they still have items in their cart.

I'm working on a shopping cart page and I'd like an alert to be displayed when the user tries to leave the page when they still have items in their cart.

When the cart is empty, t开发者_运维百科here's a div with an id of, for example, id="noItems".

Here's the alert I'm working with now that pops up every time you try to leave the page:

<script type="text/javascript">

   function unloadPage(){
       return "You may still have items in your shopping cart.";
   }

   window.onbeforeunload = unloadPage;

</script>

So is there a way to only show the alert when that id is not present on the page?


Should work -

function unloadPage(){
    if ($("#noItems").length){
      return "You may still have items in your shopping cart.";
    }
}

window.onbeforeunload = unloadPage;


You could try: -

function unloadPage(){
    if ($("#noItems").length > 0){
      return "You may still have items in your shopping cart.";
    }
}

 window.onbeforeunload = unloadPage;
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号