Setting focus on a button is not working

无人久伴 提交于 2019-12-22 02:04:08

问题


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

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

回答1:


Microsoft decided that they don't like e.keyCode and instead have their own syntax, 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?
    }
});



回答2:


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

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

with

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

This, in conjunction with using e.which with e.keyCode as Blender suggested should fix your issue.




回答3:


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

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




回答4:


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



来源:https://stackoverflow.com/questions/7802510/setting-focus-on-a-button-is-not-working

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!