如何使用jQuery包装每个项目的两个项目?

时间:2013-03-18 06:11:22

标签: jquery drupal-6 jquery-1.3

我想将<h2><table>的每一组包装在自己的<div>中,以便我可以使用CSS操作新容器。

以下是我正在使用的HTML的简化版本:

<div>
<h3></h3>
<h2 class="product-line-term-name">Product 1</h2>
<table class="views-view-grid"></table>
<h3></h3>
<h2 class="product-line-term-name">Product 2</h2>
<table class="views-view-grid"></table>
<h3></h3>
<h2 class="product-line-term-name">Product 3</h2>
<table class="views-view-grid"></table>
</div>

注意:我只处理主题层,所以jQuery(版本1.3.2)和CSS是我的工具。

3 个答案:

答案 0 :(得分:2)

在这种情况下,您可以使用nextUntilwrapAll

$('h3').each(function(){
    $(this).nextUntil('h3').wrapAll('<div class="example" />');
});

演示:http://jsfiddle.net/9w9Sp/

答案 1 :(得分:0)

看看这段代码

jQuery.each($('.product-line-term-name'), function(i, val) {
   //Create new element 
    var div = "<div>" + $(this)[0].outerHTML + $(this).next()[0].outerHTML + "</div>";  

    $(this).prev().after(div);
    $(this).next().remove();
    $(this).remove();
});

See fiddle

答案 2 :(得分:0)

我认为以下代码将满足您对jQuery 1.3.2的目的:

var h3_length = $('h3').length;

for(var i= h3_length - 1; i>= 0; i--) {
    $('h3').eq(i).nextAll().not(".test, h3").wrapAll('<div class="test" />');
}