如何在使用Javascript离开页面之前调用函数 [英] How to call a function before leaving page with Javascript

查看:74
本文介绍了如何在使用Javascript离开页面之前调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在离开页面之前执行一个函数,而不显示仅使用 Javascript 的确认弹出窗口。我已尝试使用下面的代码,但它无效或使用 onbeforeunload ,但它始终显示弹出窗口。

I would like to execute a function before leaving page without showing a confirmation popup with Javascript only. I've tried with the code below but it didn't work or with the onbeforeunload but it always shows the popup.

var result = 'test';

if(window.onbeforeunload == true)
{
    result = 'test1';
    alertmess();
}

function alertmess() {
    alert(result);
}

//window.onbeforeunload = function() { 
//  return result; 
//}


推荐答案

你随时可以打电话离开页面之前你的功能。

You can always call your function before leaving the page.

function myfun(){
     // Write your business logic here
     console.log('hello');
}

onbeforeunload:

onbeforeunload:

window.onbeforeunload = function(){
  myfun();
  return 'Are you sure you want to leave?';
};

或者使用jQuery:

Or with jQuery:

$(window).bind('beforeunload', function(){
  myfun();
  return 'Are you sure you want to leave?';
});

这只会询问用户是否要离开页面,如果用户不想重定向,他们选择留在页面上。如果他们选择离开,浏览器将转到他们告诉它的位置。

This will just ask the user if they want to leave the page or not, you cannot redirect them if they select to stay on the page. If they select to leave, the browser will go where they told it to go.

您可以在卸载页面之前使用onunload来执行操作,但是您无法重定向那里(Chrome 14+阻止onunload内的警报):

You can use onunload to do stuff before the page is unloaded, but you cannot redirect from there (Chrome 14+ blocks alerts inside onunload):

window.onunload = function() {
    myfun();
    alert('Bye.');
}

或者使用jQuery:

Or with jQuery:

$(window).unload(function(){
  myfun();
  alert('Bye.');
});

这篇关于如何在使用Javascript离开页面之前调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆