简体   繁体   中英

Focus loaded element with jQuery

I want to replace a html element with jQuery's load method and want to focus an input element within the loaded elements with the class .focus . It is possible that there is more than one element with the class .focus , so it is important to select within the loaded element.

I tried the following but it doesn't work:

  paragraphToBeReplaced.load(
    "/some/url", 
    function(event) { event.data.contents(".focus").focus(); }
  );

How can I set the focus to a loaded element? I'm using jQuery 1.7.1.

Within the load callback this is the element that new content is being loaded into. Using find() can search within this element for your class

paragraphToBeReplaced.load( "/some/url",    function() { 
         $(this).find(".focus").focus();
});

Since you already have a reference to the element into which you load the new content, you could use it again as a context:

paragraphToBeReplaced.load("/some/url", function(event) { 
    $(".focus", paragraphToBeReplaced).focus(); 
});

This should work, since the callback function is executed after the HTML returned by the URL has been inserted into the element.

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