2015-07-22 30 views
2

我嘗試在startpost和endpost div之間包裝所有內容我使用nextUntil和wrapAll,但結果是包裝內容之間沒有自由文本我該如何解決?jQuery wrap所有內容包括兩個標籤之間的文本

$('.startpost').nextUntil('.endpost') 
 
     .wrapAll('<div style="background:red" class="shortpost"></div>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="post"> 
 
    <div class="startpost"></div> 
 
    <a href="http://www.example.com"></a> Hello world!<br>Hello world! 
 
    <div class="endpost"></div> 
 
</div>

+0

可以清理預計結果各的「Hello World!」文本被包裹在「shortpost」'div'中? – guest271314

回答

1

按jQuery文檔: http://api.jquery.com/wrapall/

環繞的跨度對象的新創建的樹。注意在這個例子中跨度之間的任何內容都被忽略了(紅色文本)。即使跨度之間的空白也被忽略。

你可以/應該做的是把"Hello world!<br>Hello world!"放在<span>之內。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
<div class="post"> 
    <div class="startpost"></div> 
    <a href="http://www.example.com"></a> <span>Hello world!<br>Hello world!</span> 
    <div class="endpost"></div> 
</div> 

這將得到按預期包裹。

雖這麼說,你可以做你想做的不同的方式(如果你想排除startpost,endpost):

var inArea = false; 
$(".post").contents().each(function() { 
    console.log($(this)); 
    if ($(this).hasClass('startpost')) 
     inArea = true; 
    else if ($(this).hasClass('endpost')) 
     inArea = false; 
    else if (inArea) 
     $(this).wrap('<div style="background:red" class="shortpost"></div>'); 
}); 

或:

var inArea = false; 
$(".post").contents().each(function() { 
    console.log($(this)); 
    if ($(this).hasClass('startpost')) 
     inArea = true; 
    if (inArea) 
     $(this).wrap('<div style="background:red" class="shortpost"></div>'); 
    if ($(this).hasClass('endpost')) 
     inArea = false; 
}); 
如果要包括他們

+1

這些示例將每個元素分開包裝(demos [1](http://jsfiddle.net/Mottie/71hj3f7d/2/)&[2](http://jsfiddle.net/Mottie/71hj3f7d/3/)) – Mottie

+0

會更好地插入wrap元素並進行附加。唯一的問題可能是任何現有事件的損失 – charlietfl

3

爲什麼不只是使用wrapInnerdemo)?

$('.post').wrapInner('<div style="background:red" class="shortpost"></div>'); 

更新:如果你不想包含開始&結束後的元素,試試這個(demo):

$('.post').each(function() { 
    var include = false; 
    $(this).contents().filter(function() { 
     var c = this.className; 
     if (/startpost|endpost/.test(c)) { 
      include = c === 'startpost'; 
      return false; 
     } 
     return include && (this.nodeType === 3 || this.nodeType === 1); 
    }).wrapAll('<div style="background:red" class="shortpost"></div>'); 
}); 
+0

因爲你正在包裝「post」的整個內部部分,包括「startpost」之前和「endpost」之後的任何內容。 –

1

這裏,將首套任何文本節點解決方法那是<span>中的郵政集裝箱的孩子,所以他們將被包括在包裝中:

$('.post').contents().each(function() { 
    if (this.nodeType === 3) { 
     $(this).wrap('<span>'); 
    } 
}).end().find('.startpost') 
    .nextUntil('.endpost') 
    .wrapAll('<div style="background:red" class="shortpost"></div>'); 

它留下一些空的跨度,由於空格和換行,但與一些適應這些必要時

DEMO

相關問題