JQuery Selector on Dynamically Added Element

孤街醉人 提交于 2019-12-20 16:55:15

问题


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.

For example:

If I have HTML:

<div id="bar">
 World!
</div>

Then I create a new element and insert it in to DOM:

var foo = '<div id="foo">Hello</div>';
$("#bar").before(foo);

I end up with this:

<div id="foo">Hello</div>
<div id="bar">
 World!
</div>

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");

Then myHappyEl will be undefined. JQuery doesn't see it, presumably because it go attached after DOM was loaded.

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).


回答1:


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.



来源:https://stackoverflow.com/questions/18698842/jquery-selector-on-dynamically-added-element

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!