jQuery的集中在动态内容? [英] jquery set focus on dynamic content?

查看:108
本文介绍了jQuery的集中在动态内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在jquery中,我添加了一个< li> 元素到一个无序的列表中。

我专注于新创建的< li>



如果我这样做:

  $(ul)。append('< li>< input type =textvalue =Hi!><< ; /立GT;'); 
$(li:last)。focus(); //无法正常工作,因为新的< li>如上所述,重点不起作用。

我知道jquery 1.4.2有一个 live()事件处理程序,它允许您加载事件处理程序动态添加元素,但我我不知道我在做什么错:

pre $ $(document).ready(function(){

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


解决方案

焦点。默认情况下,列表项不能。这就是为什么你的第一个例子失败了,不是因为它不在DOM中(它在DOM中 ,那就是 append )一般来说,你应该使用设计来保持焦点的元素(例如,将焦点设置为输入而不是列表项目)。你也可以(但是这是向下兼容的,不太合乎逻辑)使用HTML5的 tabindex (可能将其设置为 0 )。

onload 将不起作用,因为列表项不会加载外部内容。


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 (i.e. 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.

这篇关于jQuery的集中在动态内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆