页面重新加载时是否可以触发JavaScript函数?

3

当用户尝试重新加载当前页面时,是否可能触发JavaScript函数?


4
这是什么意思?你想做什么?你是指调用一个 JavaScript 函数吗? - Felix Kling
请澄清一下?写JavaScript在重新加载时?那是什么意思?动态编写JS?还是您的意思是使用JS重新加载页面? - Joseph
@fskreuz:不,当用户在浏览器中点击重新加载选项卡时,我想在执行重新加载当前页面之前执行一个函数。 - Justin John
每次导航离开页面时,执行该函数是否可以? - Purag
2个回答

3
您的意思是确认一个“unload”,在用户离开当前页面之前执行一个函数。
<html>
<head>

<script type="text/javascript">
function mymessage()
{
    //this is the sample function code executed on "unload"
    alert("This message was triggered from the onunload event")
}
</script>
</head>

<body onunload="mymessage()">

<p>close this window</p>
</body>

</html>

或者,使用jQuery版本http://api.jquery.com/unload/


1

很难推断出你想要什么,但是根据你在评论中提到的,你想要在页面刷新之前执行一个函数,你可以使用unload

$(window).unload(function() {
  alert('Handler for .unload() called.');
}); 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接