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;
精彩评论