合并段落

时间:2014-01-21 04:41:51

标签: javascript jquery

我是Jquery的新手,我的要求是将两个段落合并为单个段落。我尝试使用以下代码。

<p>This is first para text </p>
<p>This is second para text </p>
<p>This is third para text.</p>

<p>This is first para text This is second para text This is third para text.</p>

它不起作用。有什么想法吗?

5 个答案:

答案 0 :(得分:5)

只有一行代码:

$('p').contents().unwrap().wrapAll('<p>');

See the demo.

答案 1 :(得分:2)

this小提琴上查看。

<强> HTML:

<div class="singles">
    <p>This is first para text</p>
    <p>This is second para text</p>
    <p>This is third para text.</p>
</div>
<div class="combined"><p></p></div>

<强> JavaScript的:

$('.singles p').each(function() {
    $('.combined p').append($(this).html() + ' ');
});

答案 2 :(得分:2)

您只需使用receiver

.text()功能即可

尝试,

$('p.single').text(function(_,xText){
    $('p.merged').append(xText);
});

DEMO

答案 3 :(得分:2)

另一种变体

<强> HTML

<p class="single">This is first para text </p>
<p class="single">This is second para text </p>
<p class="single">This is third para text.</p>
<p class='merged'></p>

<强> JS

$('.merged').text($('.single').text());

答案 4 :(得分:1)

您可以使用 appendTo()

$('p.source').each(function(){
   $(this).text().appendTo('p.target');
});