jQuery仅在id不存在时卸载警报

时间:2011-10-07 12:49:19

标签: javascript jquery alert

我正在购物车页面上工作,当用户在购物车中仍有商品时试图离开页面时,我想要显示提醒。

当购物车为空时,会有一个ID为id="noItems"的div。

以下是我现在正在处理的警报,每次您尝试离开页面时都会弹出警告:

<script type="text/javascript">

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

   window.onbeforeunload = unloadPage;

</script>

那么有没有办法只在页面上没有该ID时显示警告?

2 个答案:

答案 0 :(得分:0)

您可以尝试: -

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

 window.onbeforeunload = unloadPage;

答案 1 :(得分:0)

应该有效 -

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

window.onbeforeunload = unloadPage;