javascript JQuery 附加到动态创建的元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13726690/
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
JQuery Append To Dynamically Created Element
提问by jmease
I am dynamically appending a div
element to an existing div
. But immediately following that, I need to append another div
to the div
I just created dynamically. But I can't seem to find the dynamically created div
in order to append to it. I assume maybe the DOM isn't aware of that div
yet since I just made it. How do I do this?
我动态地将一个div
元素附加到现有的div
. 但紧接着,我需要将另一个附加div
到div
我刚刚动态创建的。但我似乎无法找到动态创建div
的以附加到它。我想也许 DOM 还没有意识到这一点,div
因为我刚刚制作了它。我该怎么做呢?
var serialModel = "Test Test";
$("#existingDiv").append("<div id = '" + serialModel + "'></div>");
$("#" + serialModel).append("<div>content here</div>")
The last line doesn't do anything. The second line produces the new div, but then I can't find it to append to it.
最后一行没有做任何事情。第二行生成新的 div,但我找不到它附加到它。
回答by VisioN
What if you do it vice versa:
如果你反过来做呢:
$("<div />", { id : serialModel }) // create `<div>` with `serialModel` as ID
.append("<div>content here</div>") // append new `<div>` to it
.appendTo("#existingDiv"); // append all to `#existingDiv`