javascript - 有没有更好的方法在 JavaScript 和/或 jQuery 中对此进行编码?

标签 javascript jquery

这里是:

//Disable KeyboardNavigation
document.getElementById("author").onfocus = function() { 
document.onkeyup = null;
};
document.getElementById("email").onfocus = function() { 
document.onkeyup = null;
};
document.getElementById("url").onfocus = function() {
document.onkeyup = null;
};
document.getElementById("comment").onfocus = function() {
document.onkeyup = null;
};

//Enable KeyboardNavigation
document.getElementById("author").onblur = function() {
document.onkeyup = KeyCheck;
};
document.getElementById("email").onblur = function() { 
document.onkeyup = KeyCheck;
};
document.getElementById("url").onblur = function() { 
document.onkeyup = KeyCheck;
};
document.getElementById("comment").onblur = function() { 
document.onkeyup = KeyCheck;
};

我相信用循环编写更好的代码绝对是可能的,但我真的不知道如何让它工作。我尝试了以下方法:

var formfields= ["author", "email", "url", "comment"];
for (i=1; i<=3; i++){
//Don't really know what to put in here.
}

预先感谢您的帮助!

编辑:完整代码如下。你应该知道 I got some help得到这个结果:

document.onkeyup = KeyCheck;       

var pages = [
"http://", 
"http://", 
"http://", 
"http://", 
"http://"];

function leftarrowpressed() {
location.href = pages[ Math.max(0, 0 - 1) ]; 
//The second '0' here changes from 0 to 4, according to the page.
}

function rightarrowpressed() {
location.href = pages[ Math.min(pages.length - 1, 0 + 1) ];
//The second '0' here changes from 0 to 4, according to the page.
}

function KeyCheck(e)
{
   var KeyID = (window.event) ? event.keyCode : e.keyCode;

   switch(KeyID)
   {

// left arrow key
     case 37:
     leftarrowpressed();    
      break;

//  right arrow key
      case 39:
      rightarrowpressed(); 
      break; 
   }
}

希望这能对您有所帮助。顺便说一句,谢谢大家。我真的不知道该选择哪种解决方案。

最佳答案

看起来您正在做的是试图防止输入元素中的击键影响导航。你可以做的是检查 event.targetKeyCheck并且仅在未由 input 触发时才执行该操作元素。

function KeyCheck(e) {
    var target = e ? e.target : event.srcElement, //standards vs IE
        tagname = target.tagName.toLowerCase();
    if( tagname !== "input" && tagname !== "textarea" && tagname !== "select") {
        //Not from an input, NAVIGATE!
    }
}

关于javascript - 有没有更好的方法在 JavaScript 和/或 jQuery 中对此进行编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9855698/

相关文章:

javascript - 右键单击 JavaScript 不适用于 PHP 中的表格

javascript - 将按钮添加到 jqgrid 列标题

jquery - 谷歌地图街景全景滚轮错误仍然捕获滚轮

javascript - Google 地球插件上下文菜单

javascript - 替换功能只能使用一次(javascript)

javascript - jQuery 表单克隆,如何阻止值被复制

JavaScript 触发的 UpdatePanel 未正确更新

javascript - 如何通过 id 注册删除 dojo 小部件,但未在任何 DOM 节点中引用

javascript - 我是 JavaScript 的新手。有人可以向我解释一下这个语法在做什么 ()()

javascript - jQuery 手动调整大小的 DIV