js或者jq怎么实现在关闭页面 和 关闭浏览器 时执行指定的函数

$(window).bind('beforeunload', function () {

    return '您输入的内容尚未保存,确定离开此页面吗?';

});

找到的这样一种办法,实现的效果如下:

https://img.mukewang.com/5c4ab6aa0001da4c08000420.jpg

我希望点击按钮【离开页面】时执行自己的函数或者代码!
还有就是beforeunload兼容性如何!

江户川乱折腾
浏览 2614回答 1
1回答

皈依舞

先说兼容,找到了以下代码//提示用户是否离开此页面(关闭、刷新或者点击后退等)window.addEventListener("beforeunload", function (e) {&nbsp; var confirmationMessage = '确定离开此页吗?本页不需要刷新或后退';&nbsp;&nbsp; (e || window.event).returnValue = confirmationMessage;&nbsp; &nbsp; &nbsp;// Gecko and Trident&nbsp; return confirmationMessage;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Gecko and WebKit});再说浏览器页面关闭之后做的事 因为这个函数的确认,和取消都是别人给的。你无法去操作可以改用另外一种方式:<html><head><script type="text/javascript">&nbsp; &nbsp; function show_confirm()&nbsp; &nbsp; {&nbsp; &nbsp; var r=confirm("要离开此页吗!");&nbsp; &nbsp; if (r==true)&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; alert("你同意了!");&nbsp; &nbsp; &nbsp; &nbsp; //关闭前干掉别的&nbsp; &nbsp; &nbsp; &nbsp;window.close();//关闭&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; alert("你不同意!");//&nbsp; &nbsp; &nbsp; &nbsp; //能做点别的&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; </script></head><body><input type="button" onclick="show_confirm()" value="Show a confirm box" /></body></html>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript