我该如何重写html元素的onkeydown? [英] How can I rewrite onkeydown on the html element?

查看:110
本文介绍了我该如何重写html元素的onkeydown?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我继承了一个应用程序,它在窗口弹出窗口中实现了禁用F5。

 < body onkeydown =disableF5(); > 

然而,如果用户在窗口下方点击正文并按下F5,页面仍会刷新。 / p>

我将函数调用移动到

 < html onkeydown = disableF5();> 

现在F5被禁用,一切都按预期工作。



然而,这并不是获得代码的最佳地方,如果我可以在< script> 部分中做下面的事情,我更喜欢它,所以我可以添加注释,也可以将其移至外部文件。

  $(html)。attr(onkeydown, disableF5();); 

这段jQuery没有按预期工作,所以我现在一直在坚持。 / p>

有没有一种方法可以设置< html> 元素的属性?



编辑:我想我会在这里抛出我的disableF5()函数。

  function disableF5(){
if(window.event&& window.event.keyCode == 116){
window.event.cancelBubble = true;
window.event.returnValue = false;
window.event.keyCode = 0;
window.status =所有弹出窗口都禁用F5;
返回false;


$ / code $ / pre

解决方案

<$ p $ ('keydown',function(){disableF5();});} $('html')。

请参阅 $ .bind()的文档



编辑 - 中等详细解释:



HTML onstuff 属性在加载DOM时评估。在事后添加它们没有任何作用。因此,必须使用正确的JS事件绑定。


I inherited an application that implements disabling F5 in a window popup.

<body onkeydown="disableF5();">

However if the user clicks below the body in the window and presses F5 the page will still refresh.

I moved the function call to

<html onkeydown="disableF5();">

and now F5 is disabled and everything is working as expected.

However this is not the best place to have code and I would prefer it if I could do something like below in my <script> section so I can add comments and perhaps move it to an external file.

$("html").attr("onkeydown", "disableF5();");

This snippet of jQuery does not work as expected however so I'm currently stuck at the moment.

Is there a way I can set the attributes of the <html> element?

Edit: I thought I would throw my disableF5() function in here.

function disableF5() {  
   if (window.event && window.event.keyCode == 116) { 
        window.event.cancelBubble = true;
        window.event.returnValue = false;
        window.event.keyCode = 0;
        window.status = "F5 is disabled on all popups";
        return false;
   }   
}

解决方案

$('html').bind('keydown', function(){ disableF5(); });

See the documentation for $.bind()

Edit – Moderately verbose explanation:

HTML onstuff attributes are evaluated as the DOM is loaded. Adding them post-factum doesn't have any effect. Thus, proper JS event binding must be used.

这篇关于我该如何重写html元素的onkeydown?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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