简体   繁体   English

仅在表单元素外部触发jquery键事件

[英]trigger jquery key event only outside form element

Is it possible to trigger a key event only outside a form element? 是否可以仅在表单元素外部触发键事件?

Background: I have a code that loads the next page when the right key is pressed. 背景:我有一个代码,可以在按下右键时加载下一页。 But I don't want to trigger that event if somebody is using that key in a form element. 但是,如果有人在表单元素中使用该键,我不想触发该事件。

current code: 当前代码:

$(document).keydown(function(e){
    if (e.keyCode == 37) { 

        var url = $('a#left').attr("href");

        if (url != '') { // require a URL
                window.location = url; // redirect
        }

    return false;
    }

    if (e.keyCode == 39) { 

        var url = $('a#right').attr("href");

        if (url != '') { // require a URL
                window.location = url; // redirect
        }

    return false;
    }
});

Here is a basic example of the concept. 这是该概念的基本示例。 Your simply adding an event handler to the document and checking that its target does not have a parent that is a form. 您只需将事件处理程序添加到文档中,并检查其目标对象是否没有作为表单的父级。

HTML HTML

<form>
    Inside form
    <input/>
</form>
Outside form
<input />

Javascript 使用Javascript

    $(document).keyup(function(event){
        if($(event.target).parents("form").length == 0){
           alert("here");
        }
    });

Working POC: http://jsfiddle.net/48NYE/ 工作POC: http : //jsfiddle.net/48NYE/

This concept can be easily applied to the script you have provided. 此概念可以轻松应用于您提供的脚本。

Modification for your Script 修改脚本

$(document).keydown(function(e){
    var outsideForm = $(e.target).parents("form").length == 0;
    if (e.keyCode == 37 && outsideForm) { 

        var url = $('a#left').attr("href");

        if (url != '') { // require a URL
                window.location = url; // redirect
        }

    return false;
    }

    if (e.keyCode == 39  && outsideForm){ 

        var url = $('a#right').attr("href");

        if (url != '') { // require a URL
                window.location = url; // redirect
        }

    return false;
    }
});

If you have other fields outside your form this might be quite useful I hope 如果您在表单之外还有其他字段,我希望这可能会很有用

LIVE DEMO 现场演示

document.onkeyup = function( ev ){

  var key = ev.which || ev.keyCode ,
      aID = { 37:"left", 39:"right" }; 

  if( ! (/INPUT|TEXTAREA/i.test(ev.target)) && aID[key]) {
     var url = document.getElementById( aID[key] ).getAttribute('href');
     window.location = url;
  }

};

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

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