加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Windows > 正文

使用window.onbeforeunload事件中的window.event.keyCode在javas

发布时间:2020-12-14 04:12:25 所属栏目:Windows 来源:网络整理
导读:我正在创建一个MVC应用程序.在关闭应用程序(即窗口/选项卡)时,将会话中的变量设置为null,但在刷新应用程序时却没有. 我通过以下代码尝试了它. script type="text/javascript" window.onbeforeunload = function (e) { e = e || window.event; if (window.eve
我正在创建一个MVC应用程序.在关闭应用程序(即窗口/选项卡)时,将会话中的变量设置为null,但在刷新应用程序时却没有.
我通过以下代码尝试了它.
<script type="text/javascript">
           window.onbeforeunload = function (e) {
               e = e || window.event;
               if (window.event.keyCode == 116) {
                   alert("f5 pressed");
               }
               else {
                   alert("Window closed");
                   //call my c# code to make my variable null,eg:Session["myVariable"] = null;
               }  
           };
</script>

但是当按下F5时,“window.event.keyCode”始终为0而不是116.
因为我的变量即使按F5按键也变为空,这不是我的要求.

即使当应用程序(即网页)关闭时,即使它是0(这可能是正确的).

请注意,代码的上述部分位于.cshtml文件中.

任何人都可以告诉我哪里错了吗?

你必须听取不同的事件,如果你想让它工作crossborwser你必须每次按下按键事件,而不是负载:
document.onkeydown = fkey;
document.onkeypress = fkey
document.onkeyup = fkey;

var wasPressed = false;

function fkey(e){
        e = e || window.event;
       if( wasPressed ) return; 

        if (e.keyCode == 116) {
             alert("f5 pressed");
            wasPressed = true;
        }else {
            alert("Window closed");
        }
 }

这是一个演示:http://jsfiddle.net/FSrgV/1/embedded/result/

但如果您只是想知道用户是否退出页面,您只需使用window.onbeforeunload:https://developer.mozilla.org/en-US/docs/DOM/window.onbeforeunload

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读