jQuery 将焦点设置在按钮上不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7802510/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 00:16:52  来源:igfitidea点击:

Setting focus on a button is not working

jquerysetfocus

提问by Lamps

I am trying to set the focus to a button while the user presses the Enterkey in the text box. But it is not working. I am using the Internet Explorer 8 browser. Am I missing something?

我试图在用户按下Enter文本框中的键时将焦点设置为按钮。但它不起作用。我使用的是 Internet Explorer 8 浏览器。我错过了什么吗?

$("input.Box").live('keydown', function(e) {
    if (e.keyCode == 13) {
        e.preventDefault(); 
        $("#button").focus(); // Not working?
    }
});

采纳答案by Blender

Microsoft decided that they don't like e.keyCodeand instead have their own syntax, e.which.

微软决定他们不喜欢e.keyCode,而是有自己的语法,e.which.

You have to check for both:

您必须检查两者:

$("input.Box").live('keydown', function(e) {
    var keyCode = (window.event) ? e.which : e.keyCode;

    if (keyCode == 13)
        e.preventDefault(); 
        $("#button").focus(); // Not working?
    }
});

回答by Ankit Soni

The problem is that IE is not able to respond quickly enough, so you need to add a small delay between when the livefunction is entered, and when .focus()is called. So, replace

问题是 IE 的响应速度不够快,所以你需要在live函数进入和.focus()调用之间添加一个小的延迟。所以,更换

$("#button").focus();

$("#button").focus();

with

setTimeout(function () {
 $('#button').focus();
}, 100);

This, in conjunction with using e.whichwith e.keyCodeas Blender suggested should fix your issue.

e.whiche.keyCodeBlender 建议的with一起使用应该可以解决您的问题。

回答by griegs

Are you sure the name is correct? .NEThas a habit of renaming things. You don't specify the language or environment.

你确定名字正确吗?.NET有重命名事物的习惯。您没有指定语言或环境。

Try to use the class selector. Give the button a class name of class="Test"and then select using $(".Text").focus().

尝试使用类选择器。给按钮一个类名,class="Test"然后选择 using $(".Text").focus()

回答by Chad

Make sure the DOM is ready, element exists, before attempting to set focus.

在尝试设置焦点之前,请确保 DOM 已准备就绪,元素存在。