开发者

jQuery unload alert only when an id is not present

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜