用jQuery添加另一个div

Sar*_*a44 2 jquery append prepend

我循环遍历XML文件中的每个相关标记并执行此代码.

$('<div class="product_image"></div>').html('<a href="'+url+'"><img src='+urlZoomImage+' /></a>').appendTo('#content');
$('<div class="product_title"></div>').html('<a href="'+url+'">'+title+'</a>').appendTo('#content');
Run Code Online (Sandbox Code Playgroud)

我想用一个名为product_box的div来包围product_image和product_title,如下所示:

<div id="content">
  <div class="product_box">
    <div class="product_image">My image code</div>
    <div class="product_title">My title code</div>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

只有内容div写在HTML中,它必须保持这样(我不能在那里写product_box代码,因为它是在每个成功的查找上生成的).我该怎么做呢?

提前致谢.

Rip*_*xus 5

当您使用jQuery创建HTML元素时,您很容易迷失在代码中.尝试将单独的元素保存在变量中,并在初始化后进行排列.像这样:

var div_box = $('<div></div>').addClass('product_box');
var div_image = $('<div></div>').addClass('product_image').html('<a href="'+url+'"><img src='+urlZoomImage+' /></a>');
var div_title = $('<div></div>').addClass('product_title').html('<a href="'+url+'">'+title+'</a>');
$('#content').append(div_box.append(div_image).append(div_title));
Run Code Online (Sandbox Code Playgroud)