【问题标题】:Adding another div with jQuery使用 jQuery 添加另一个 div
【发布时间】:2012-11-02 22:35:52
【问题描述】:

我正在遍历 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');

我想用一个名为 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>

只有内容 div 是用 HTML 编写的,并且它必须保持这样(我不能在其中编写 product_box 代码,因为它是在每次成功查找时生成的)。我该怎么做呢?

提前致谢。

【问题讨论】:

  • 您将元素附加到 #content 元素,但您有一个类为 content 的 div 元素!错别字?
  • 谢谢,这是一个错字,现在已修复 OP。

标签: jquery append prepend


【解决方案1】:

当您使用 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));

【讨论】:

  • 是的,非常感谢。刚刚编辑了最后一行以使其工作: $('#content').append(div_box.append(div_image).append(div_title));
【解决方案2】:
var box = $('<div class="product_box"></div>');
var product_image = $('<div class="product_image"></div>').html('<a href="'+url+'"><img src='+urlZoomImage+' /></a>');
var produc_title = $('<div class="product_title"></div>').html('<a href="'+url+'">'+title+'</a>');

box.append(product_image,product_title).appendTo('.content');

Reference

【讨论】:

    【解决方案3】:

    只需使用相同的语法创建.product_box:元素,然后将其他内容附加到那个元素,而不是#content元素。

    var product_box = $('<div />', {'class' : 'product_box'}).appendTo('#content');
    $('<div class="product_image"></div>').html('<a href="'+url+'"><img src='+urlZoomImage+' /></a>').appendTo(product_box);
    $('<div class="product_title"></div>').html('<a href="'+url+'">'+title+'</a>').appendTo(product_box);
    

    【讨论】:

      猜你喜欢
      • 2011-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-03
      • 2016-07-22
      • 1970-01-01
      • 1970-01-01
      • 2020-11-05
      相关资源
      最近更新 更多