按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;
});
如果要包括他們
。
可以清理預計結果各的「Hello World!」文本被包裹在「shortpost」'div'中? – guest271314