动态添加元素上的jQuery选择器 [英] JQuery Selector on Dynamically Added Element
问题描述
我无法弄清楚如何诱使JQuery选择页面加载后动态插入DOM的元素(不是绑定处理程序).
I can't figure out how to coax JQuery in to selecting an element (not binding handlers) that is dynamically inserted in to the DOM after the page loads.
例如:
如果我有HTML:
<div id="bar">
World!
</div>
然后我创建一个新元素并将其插入到DOM中:
Then I create a new element and insert it in to DOM:
var foo = '<div id="foo">Hello</div>';
$("#bar").before(foo);
我最终得到了这个
<div id="foo">Hello</div>
<div id="bar">
World!
</div>
稍后,我可能想对插入的元素做一些不同的事情,使用JQuery来操纵该新元素.但是,如果我尝试这样做:
Later on I might want to do something different with the element I inserted, using JQuery to manipulate that new element. But if I try to do:
myHappyEl = $("#foo");
然后myhappyEl将不确定. JQuery没有看到它,大概是因为它在DOM加载后就被附加了.
Then myHappyEl will be undefined. JQuery doesn't see it, presumably because it go attached after DOM was loaded.
我已经看到很多解决可能相关但微妙的问题的建议,其中的解决方案是在元素出现时使用.live()/.on()附加事件侦听器.如果我想捕获单击事件或其他事件,那将是很棒的选择,但是我没有.我希望能够选择动态添加的元素.
I've seen lots of suggestions addressing a possibly related but subtly different issue, wherein the solution is to use .live()/.on() to attach an event listener when an element comes in to being. That would be brilliant if I wanted to capture a click event or something, but I don't; I want to be able to select the dynamically added element(s).
推荐答案
插入元素后,您必须分配该变量,如下所示:
You'll have to assign that variable after the element has been inserted, like so:
var myHappyEl = $("#foo"); //Nothing, it isnt there
var foo = '<div id="foo">Hello</div>';
$("#bar").before($(foo));
myHappyEl = $("#foo");
否则,该元素在页面上不存在.
Otherwise, the element doesn't exist on the page.
这篇关于动态添加元素上的jQuery选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!