javascript 使用 jquery 将动态创建的 div 添加到另一个 div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6819376/
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
Adding a dynamically created div to another div with jquery
提问by Bring Coffee Bring Beer
I am creating two divs:
我正在创建两个 div:
var div_day=document.createElement("div");
var div_dateValue=document.createElement("div");
I then want to add div_day to an existing calendar div and div_dateValue to div_day:
然后我想将 div_day 添加到现有日历 div 并将 div_dateValue 添加到 div_day:
$('#calendar').append(div_day)
$(div_day).append(div_dateValue);
div_day gets added to calendar, but div_dateValue does not get added to div_day, and the script stops there. No errors in the console but it is in a loop and should have more div_days (each with a unique id). I am new to jquery so any help is appreciated.
div_day 被添加到日历中,但 div_dateValue 没有被添加到 div_day,并且脚本在那里停止。控制台中没有错误,但它处于循环中并且应该有更多的 div_days(每个都有一个唯一的 id)。我是 jquery 的新手,因此感谢您的任何帮助。
In my search I have found how to add divs, but not to add a dynamically created div to another dynamically created div.
在我的搜索中,我找到了如何添加 div,但没有将动态创建的 div 添加到另一个动态创建的 div。
Thanks for your help!
谢谢你的帮助!
Kevin
凯文
回答by najam
$('<div><div></div></div>').appendTo("#calendar");
Try this and mark it as answer if it helps
试试这个,如果有帮助,将其标记为答案
回答by Joseph Marikle
div_day.appendChild(div_dateValue)
$('#calendar').append(div_day)
回答by Jeff B
Something else must be going on (even with your missing semi-colon). Your example works fine here:
必须有其他事情发生(即使您缺少分号)。你的例子在这里工作正常:
But, instead of creating divs with straight javascript, you can do it with jQuery:
但是,您可以使用 jQuery 来完成,而不是使用直接的 javascript 创建 div:
var div_day = $("<div>");
var div_dateValue = $("<div>");
$('#calendar').append(div_day);
$(div_day).append(div_dateValue);
Of course, you could do this in a single step:
当然,您可以一步完成:
$('#calendar').append("<div><div></div></div>");