动态添加元素上的 JQuery 选择器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18698842/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 22:15:34  来源:igfitidea点击:

JQuery Selector on Dynamically Added Element

jqueryselector

提问by Gustavo

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.

我不知道如何引导 JQuery 选择在页面加载后动态插入到 DOM 中的元素(不是绑定处理程序)。

For example:

例如:

If I have HTML:

如果我有 HTML:

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

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

然后我创建一个新元素并将其插入到 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:

稍后我可能想对我插入的元素做一些不同的事情,使用 JQuery 来操作这个新元素。但如果我尝试这样做:

myHappyEl = $("#foo");

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

那么 myHappyEl 将是未定义的。JQuery 看不到它,大概是因为它在 DOM 加载后附加。

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

我已经看到很多建议解决一个可能相关但略有不同的问题,其中解决方案是使用 .live()/.on() 在元素出现时附加事件侦听器。如果我想捕获点击事件或其他东西,那将是非常棒的,但我没有;我希望能够选择动态添加的元素。

采纳答案by tymeJV

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.

否则,该元素在页面上不存在。