使用jquery在元素后插入close div()

时间:2013-11-29 09:28:12

标签: jquery

我有如下的html结构:

<div class="address-container">
   <div class="address">
      AAAAA
   </div>
   <div class="address">
      BBBBB
   </div>
   <div class="address">
      CCCCC
   </div>
   .
   .
   .
</div>

我希望它使用jquery,当它循环到某个元素时会追加

"</div><div class='address'>"

。结构应如下所示:

<div class="address-container">
   <div class="address">
      AAAAA
   </div>
   <div class="address">
      BBBBB
   </div>
*</div>*
*<div class="address-container">*
   <div class="address">
      CCCCC
   </div>
</div>

我的代码如下所示:

$('div.address').each(function(i, e){
        var h = $(e).height();
        total_height = total_height + h;

        if(total_height >= 300){
            $(e).after('</div><div class="address-container">');
            total = 0;
        }
    });

但是上面的代码意外地产生了这样的结果(它自动打开div为关闭div而关闭div为open div class =“address-conntainer”):

<div class="address-container">
   <div class="address">
      AAAAA
   </div>
   <div class="address">
      BBBBB
   </div>
*<div></div>*
*<div class="address-container"></div>*
   <div class="address">
      CCCCC
   </div>
</div>

我的代码出了什么问题?或者你们有其他解决方案来生成我想要的html结构?任何帮助都非常感谢:)

2 个答案:

答案 0 :(得分:1)

请记住,HTML代码被解析为DOM对象。这意味着在这种情况下:

<div id="d_outer" class="address-container">
   <div class="address">
      AAAAA
   </div>
   <div class="address">
      BBBBB
   </div>
   <div class="address">
      CCCCC
   </div>
</div>

Object #d_outer包含三个子对象。将其转换为

<div id="d_outer" class="address-container">
   <div class="address">
      AAAAA
   </div>
   <div class="address">
      BBBBB
   </div>
</div>
<div id="d_outer2" class="address-container">
   <div class="address">
      CCCCC
   </div>
</div>

你必须创建一个新的div节点#d_outer2并在#d_outer2中移动#d_outer的最后一个子节点。尝试这样的事情:

$('#parentAddressContainer div.address').each(function(i, e){
            var h = $(e).height();
            total_height = total_height + h;

            if(total_height >= 300){                
             $('#parentAddressContainer').append("<div class=\"address-container\"></div>")                
             $('#parentAddressContainer div.address-container:last-child').append($(e));
             total_height = 0;
            }
        });

这是JsFiddle

答案 1 :(得分:0)

你可以通过创建一个新元素并删除旧元素然后文档准备好来完成。

原始HTML

<div class="address-container">
    <div class="address">
         AAAAA
    </div>
    <div class="address">
         BBBBB
    </div>
    <div class="address">
         CCCCC
    </div>
</div>

<强> JQuery的

var $target = $('.address-container .address');
var $container = $('<div/>').addClass('address-container');
var $elem = $('<div/>').addClass('.address').html($target.eq(2).html());
$container.append($elem);

$('.address-container').after($container);
$target.eq(2).remove();

<强> Here is the JsFiddle