Vin*_*inz 2 html javascript jquery append
我需要制作大型DIV结构并将它们附加到包装器上.但到目前为止我所看到的总是将一个 DIV元素附加到另一个元素中.
有一个空的DIV-Wrapper,用"大"DIV-Elements填充
<div class="PostWrapper">
// Content should be added to here
</div>
Run Code Online (Sandbox Code Playgroud)
我希望附加的DIV-Elements PostWrapper看起来像这样:
<div class="Post">
<div class="PostHead">
<span class="profilePicture">
<img src="../Profiles/Tom.jpg" />
</span>
<span class="userName">Tom</span>
<span class="postTime">10 minutes ago</span>
</div>
<div class="PostBody">
<p>Hey Tom, great work at the presentation last week. Well done!</p>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
所以这是一个DIV-Structure的例子,我想构建并存储在一个javascript变量中,并附加到我的包装器,如:
var postElement = $("div", {class: "Post"}).append("div", {class: "PostHead"}).append("div", {class: "PostBody"})......
Run Code Online (Sandbox Code Playgroud)
这不会像预期的那样工作.但是,如果没有过于复杂的代码,我无法想到一个简单的方法.
怎么可能呢?
您可以通过确保调用$(...)要创建的每个新元素来完成所需的操作:
var postElement = $("<div>", {class: "Post"}).append(
$("<div>", {class: "PostHead"}).append( /* head contents */ ),
$("<div>", {class: "PostBody"}).append( /* body contents */ )
);
$('#PostWrapper').append(postElement);
Run Code Online (Sandbox Code Playgroud)
NB:<div>不是div.前者用于创建元素,后者仅用于选择元素.