请在Chrome浏览器中查看我的代码,如果点击刷新,系统会提示您选择2个选项。
- 离开这个页面和
- 保持此页上
当我点击 2.留在这个页面上 按钮它必须激活我的自定义功能 displayMsg()
任何人都能为我提供解决方案吗
<script type="text/javascript">
function displayMsg() {
alert('my text..');
}
</script>
<script type="text/javascript">
window.onbeforeunload = function(evt) {
var message = 'Please Stay on this page and we will show you a secret text.';
if (typeof evt == 'undefined') {
evt = window.event;
}
if (evt) {
evt.returnValue = message;
return message;
}
trace(evt);
}
</script>
使用计时器来监听变量变量:
var vals=0;
function displayMsg() {
alert('my text..');
}
window.onbeforeunload = function evens(evt) {
var message = 'Please Stay on this page and we will show you a secret text.';
if (typeof evt == 'undefined') {
evt = window.event;
}
timedCount();
vals++;
if (evt) {
evt.returnValue = message ;
return message ;
}
trace(evt);
}
function timedCount()
{
t=setTimeout("timedCount()",100);
if(vals>0)
{
displayMsg();
clearTimeout(t);
}
}
使用计时器来监听变量变量:
var vals=0;
function displayMsg() {
alert('my text..');
}
window.onbeforeunload = function evens(evt) {
var message = 'Please Stay on this page and we will show you a secret text.';
if (typeof evt == 'undefined') {
evt = window.event;
}
timedCount();
vals++;
if (evt) {
evt.returnValue = message ;
return message ;
}
trace(evt);
}
function timedCount()
{
t=setTimeout("timedCount()",100);
if(vals>0)
{
displayMsg();
clearTimeout(t);
}
}
你可以结合使用 onbeforeunload
和 onunload
事件,在前者中设置计时器并在后者中清除它:
var showMsgTimer;
window.onbeforeunload = function(evt) {
var message = 'Please Stay on this page and we will show you a secret text.';
showMsgTimer = window.setTimeout(showMessage, 500);
evt = evt || window.evt;
evt.returnValue = message;
return message;
}
window.onunload = function () {
clearTimeout(showMsgTimer);
}
function showMessage() {
alert("You've been trolled!");
}
这是因为 onunload
当用户选择留在页面上时,事件永远不会触发。
请使用这些代码行,它可以正常工作。
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script type="text/javascript">
$(function(){
$(window).bind('beforeunload', function(){
return 'Your Data will be lost :(';
});
});
</script>