将keypress事件添加到没有JQuery的类中

时间:2016-03-20 20:34:40

标签: javascript-events keyboard-events eventhandler

下面的代码附加了点击事件处理程序,但不适用于键盘事件。我不想要document.keypress,而是想要键盘事件的特定类元素。所以我测试了#39;写出来适用于鼠标点击很好,但不适用于任何键盘事件。

  function test(className, fnCall, eventToApply){
    if(typeof document.getElementById('x').getElementsByClassName(className) !='undefined') {
                    var els = document.getElementById('x').getElementsByClassName(className);
                    for(var i = 0; i < els.length; i++) {
                        if(els[i].addEventListener) { //Undefined for keypress events
                          els[i].addEventListener(eventName,  function(e) { fnCall(e); }); }
                        else {  //Hardcode for testing
                           els[i].onclick = function(e) { fnCall(e); };     
                            els[i].onkeypress = function(e) { fnCall(e); } //doesn't work!
                        }
                    }

文档onkeypress虽然有效,但我无法在文档就绪或按键本身上设置单独的元素处理程序。

document.addEventListener('keypress', function(event){
                   //This works, but setting up events for each class type element doesn't work for keypress 
        })

换句话说,是否有相当于下面的内容,而不使用JQuery:

 document.addEventListener('keypress', function(event){
       //This works in Jquery
        $('.customClass-'+ event.keycode).click(); 
  });



document.addEventListener('keypress', function(event){
 //This doesn't register, says undefined for any event or attachEvenHandler/attachEvent    
 test('.class'+event.keycode, myFunction() , 'keypress');

 });

1 个答案:

答案 0 :(得分:0)

您可以使用此

document.addEventListener('keypress', function(event){
    var elements = document.getElementsByClassName("customClass-" + event.keycode);
    for (var i = 0; i < elements.length; i++) {
        elements[i].click();
    }
});

w3school文件