javascript创建div元素并添加内容

时间:2013-12-20 22:33:05

标签: javascript jquery

我正在尝试创建一个div元素并向其添加一些内容,并且需要在添加所有内容后显示div元素的内容。

我使用下面的代码,由于某种原因,div元素没有显示在HTML ...

http://jsfiddle.net/KVe9K/

js代码

container = $("<div/>", { "class": "container" });
$(".container").append("<b>Appended text</b>");
$(".container").append("<b>Appended text</b>");
$(".container").append("<b>Appended text</b>");
$(".container").append("<b>Appended text</b>");
$(".container").append("<b>Appended text</b>");

css代码:

.container{
    height:100px;
    width:100px;
    background-color:black;
}

2 个答案:

答案 0 :(得分:3)

  

由于某种原因,div元素没有显示在HTML ...

那是因为你从未将container放在DOM的任何地方。您已经创建了元素,但没有将其添加到页面的任何位置。

将其添加到您希望的页面。例如,这会将其添加到body元素:

container.appendTo(document.body);

...但你可能还有其他特定的地方。

另请注意,您的小提琴不起作用,因为您没有包含jQuery,因此$是未定义的符号。

这是包含jQuery 的小提琴,并将该元素附加到DOM:http://jsfiddle.net/KVe9K/1/


如果您的意思是,为什么您的append调用不起作用,这是因为该元素尚未在DOM中,因此它与.container选择器不匹配。但是你可以这样做:

container = $("<div/>", { "class": "container" });
container.append("<b>Appended text</b>");
container.append("<b>Appended text</b>");
container.append("<b>Appended text</b>");
container.append("<b>Appended text</b>");
container.append("<b>Appended text</b>");
container.appendTo(document.body); // Or whereever

Further updated fiddle

答案 1 :(得分:0)

container = $("<div/>", { "class": "container" });

这样就不会将div添加到dom元素中。

相关问题