0

我有这个代码用于在按下一个键时重定向:

$('body').bind('keyup', function(event) {
    if(event.keyCode==66){ window.location = "page.php"; }
    });

好的,但是,如果用户在页面上有一个焦点输入字段,我怎么能使它不适用?

4

4 回答 4

0
$('input').bind('keyup', function(event) {
   if(event.keyCode==66 && !($(event.currentTarget).attr('id') ==='inputElement')){ window.location = "page.php"; }
});

或者

$('input').bind('keyup', function(event) {
   if(event.keyCode==66 && !($(event.currentTarget).is(":focus"))){ window.location = "page.php"; }
});
于 2013-01-30T02:28:47.417 回答
0

您可以使用 jQuery 的:focus选择器。

$("input").is(":focus")

这里的一个例子:http: //jsfiddle.net/n1ck/CegR7/2/

$('body').bind('keyup', function (event) {
    // If 'b' is pressed & no input is focused
    if (event.keyCode == 66 && !$("input").is(":focus")) {
        alert('Redirecting');
    }
});
于 2013-01-30T02:36:07.397 回答
0

您可以测试event.target并查看它是什么类型的元素。如果是input, 不做任何事情就返回。具体来说,

if (-1 != ['INPUT', 'TEXTAREA'].indexOf(event.target.nodeName)) return;

编辑:嗯,你们确定event.currentTarget吗?我看到有几个人提到currentTarget而不是target,但并不event.currentTarget总是是body监听器绑定的元素?

于 2013-01-30T02:25:57.830 回答
0

试试这个可能。

if ( $("*:focus").is("textarea, input") ) return;
于 2013-01-30T02:27:01.037 回答