简体   繁体   中英

focus() not firing the focus event when called from jQuery(document).ready

I have a page with a large form on it and I am trying to assign the form element that has focus when the page loads. It appears to be working in that the cursor is place in the selected form element, however, the focus event is not fired. If I minimize the browser and then maximize it again the focus event is then fired, but not on jQuery(document).ready(). Any advice appreciated...

jQuery(document).ready(function()
{
    console.log("call focus");
    jQuery("#tbl_Employees").find(".employeeinfo:eq(" + IndexEmp + ")").find("tr#trSequence").find("td:eq(5)").children(":first").focus();
});    

jQuery(":input").focus(function(e)
{
    console.log("enter focus");
});    

I think you should put the $(":input") in the ready function and before the $("#tbl_Employees")

jQuery(function() { // <-- Same exact thing as `jQuery(document).ready(function () {`, just much shorter. Welcome to jQuery
    jQuery(':input').focus(function(e) {
        console.log("enter focus");
    });
    console.log("call focus");
    jQuery("#tbl_Employees").find(".employeeinfo:eq(" + IndexEmp + ")").find("tr#trSequence").find("td:eq(5)").children(":first").focus();
})

Just a guess but you're event handler should probably be placed in the document ready block too. I'm not sure where this script is located (ie in the head or at the end of the body) but if :input is not present when the event handler is called, no event will be bound.

Try this:

jQuery(document).ready(function () {

    jQuery(':input').focus(function (e) {
        console.log("enter focus");
    });

    console.log("call focus");
    jQuery("#tbl_Employees").find(".employeeinfo:eq(" + IndexEmp + ")").find("tr#trSequence").find("td:eq(5)").children(":first").focus();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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