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

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

JQuery Append To Dynamically Created Element

javascriptjquery

提问by jmease

I am dynamically appending a divelement to an existing div. But immediately following that, I need to append another divto the divI just created dynamically. But I can't seem to find the dynamically created divin order to append to it. I assume maybe the DOM isn't aware of that divyet since I just made it. How do I do this?

我动态地将一个div元素附加到现有的div. 但紧接着,我需要将另一个附加divdiv我刚刚动态创建的。但我似乎无法找到动态创建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`