简体   繁体   中英

jquery set focus on dynamic content?

In jquery I've appended a <li> element to an unordered list.

How do I focus on the newly created <li> ?

If I do the following:

$("ul").append('<li><input type="text" value="Hi!"></li>');
$("li:last").focus(); //doesn't work because new <li> isn't in dom yet

the focus doesn't work, as noted above.

I know jquery 1.4.2 has a live() event handler which allows you load event handlers to dynamically added elements, but I'm not sure what I'm doing wrong:

$(document).ready(function () {

    $('li').live('load', function () {
       alert("hi!");
       $("li:last").focus();
    });
 });

You can only set the focus to elements which can hold the focus. By default a list item cannot. This is why your first example fails, not because it isn't in the DOM (it is in the DOM, that is what append does)

In general you should use elements designed to hold the focus (ie set the focus on the input not the list item ). You can also (but this is less backwards compatible and less logical) use HTML5's tabindex (probably setting it to 0 ).

onload will not work because list items do not load external content.

你可以尝试这个, $(YourElement).trigger("focus")

This is an old post I know, but a simple way to solve this issue is to create a text input in your HTML and set its CSS to "display: none;". On the LI's click event, set the focus in this input and listen to its keypress events.

I've done it and it works like a charm.

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