使用JQuery的周围元素 - before()没有做我想要的

时间:2011-11-28 19:43:12

标签: jquery dom

我有一些HTML,我使用H1呼叫每个.each()。我想要不仅围绕着H1,而且还有下面的所有内容 - 直到下一个H1 - 带有div。

如果我尝试这样的话:

$('#presentationcontent h1').each(function (index) {
      $(this).before('<div>');

它为我关闭了div ...我想做这样的事情:

 $('#presentationcontent h1').each(function (index) {
        counter++;
        if (counter == 1) 
        {
            $(this).before('<div class="headingSections" style="border: 1px">');
        }
        else
        {
           $(this).before('</div><div class="headingSections" style="border: 1px">');
        }

希望我可以将第一个H1设置为<div>,然后将其他每一个设置为关闭<div>并打开一个新的...那样H1下的所有内容1}}包括在内。

什么吗?

2 个答案:

答案 0 :(得分:2)

尝试:

$('#presentationcontent h1').each(function (index) {
    $(this).nextUntil('h1').andSelf().wrapAll('<div/>');
    // ...
});

http://jsfiddle.net/7V2fb/1/

答案 1 :(得分:2)

对您的HTML设置进行假设,以下方法可以解决问题:

$('#presentationcontent h1').each(function() {
    $(this).nextUntil('h1').andSelf().wrapAll('<div/>');
});

以下是jsFiddle的工作原理。

相关问题