繁体   English   中英

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

[英]Is there a better way to code this in JavaScript and/or 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.
}

预先感谢您的帮助!

编辑:整个代码如下。 您应该知道, 我得到了一些帮助来实现此结果:

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; 
   }
}

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

如果使用jQuery,则可以采用更简单的方法:在KeyCheck ,检查是否有任何元素被聚焦,在这种情况下不做任何事情。 您不需要以上任何内容。

function KeyCheck(e) {
  if($("#author, #email, #url, #comment").is(":focus")) {
    return;  // ignore if any of these elements has focus
  }

  // ...
}

确保KeyCheck使用jQuery绑定KeyCheck

$("body").on("keyup", KeyCheck);

看来您正在执行的操作是试图防止输入元素中的击键影响导航。 相反,您可以做的是在KeyCheck检查event.target ,并且仅在未由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!
    }
}
var formfields= ["author", "email", "url", "comment"];
for (i=0; i<=3; i++){
      var field = document.getElementById(formFields[i]);
      field.onfocus = function() { 
          document.onkeyup = null;
      };
      field.onblur = function() { 
          document.onkeyup = KeyCheck;
      };
}

or more proper way would be to use something like this

jQuery.each("author email url comment".split(" "), function(i, name) {
    $('#' + name).focus(function() {
       // do whatever you want to do
    }).blur(function() {
      // do whatever you wnat to do
    ));
});

整洁易读:

var formfields = ["author", "email", "url", "comment"],
    i, elem,
    blur = function() {   document.onkeyup = KeyCheck; },
    focus = function() {  document.onkeyup = null;     };
for (i=0; i<=3; i++) {
    elem = document.getElementById(formFields[i]);
    elem.onblur = blur;
    elem.onfocus = focus;
}

为这些元素寻找最接近的公共父对象,并为其添加处理程序。 我们可以使用通过.on()进行委派的.on()以及方法链来将处理程序绑定到父级 (在这种情况下,所有处理程序均为2个处理程序,而不是8个处理程序,每个元素2个)对所有4个元素都生效。

var selectors = '#author, #email, #url, #comment';

$('nearest_parent_element').on('focus', selectors, function() {
    document.onkeyup = null;
}).on('blur', selectors, function() {
    document.onkeyup = KeyCheck;
});​

jQuery方式:

$("#author, #email, #url, #comment").on({
    focus: function() {
        $(document).on('keyup', null);
    },
    blur: function() {
        $(document).on('keyup', KeyCheck);
    }
});

这完全取决于您对JavaScript的熟练程度。 我建议您使用事件委托: http : //jsfiddle.net/teresko/PkCuZ/3/

看起来可能有点复杂,但是add_listener()函数将在整个代码中共享,因此有效负载实际上是这样的:

var handlers = {
    keyout: function(e){  
        var event = e || window.event, 
            target = event.target || event.srcElement;
        console.log( 'leaving ' + target.name ); 
    },
    keyin: function(e){
         var event = e || window.event, 
            target = event.target || event.srcElement;
        console.log( 'entering ' + target.name );
    }
},
container = document.getElementById('container');


add_listener( container, 'blur' , handlers.keyout );
add_listener( container, 'focus' , handlers.keyin );   

这将适用于任何数量的表单元素。

至于add_listener()函数,它包含一个针对IE的模糊/聚焦的小修复程序,并针对每个应用程序选择了使用哪种附加事件方法。 它是一种通用功能,当您需要用于连接侦听器的通用接口时,可以插入其中:

var add_listener = (function () {
    var fix = {
        'focus':    'focusin',
        'blur':     'focusout'
    };
    if ( window.addEventListener ) {
        return function ( element, type, callback ) {
            element.addEventListener(type, callback, typeof(fix[type]) !== undefined );
        };
    }else{
        return function ( element, type, callback ) {
            type = fix[type] || type;
            element.attachEvent('on' + type, callback);
        };        
    }
})();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM