2012-12-12 46 views
4

我遇到以下代码正在写入我的页面的情况。jQuery - 将所有解包的文本包装在p标签中

<div> 
    Some text here which is not wrapped in tags 
    <p>Some more text which is fine</p> 
    <p>Blah blah another good line</p> 
</div> 

在这种情况下,它似乎总是这是不被包裹在p标签这可能使解决这个更容易的第一行,尽管它每次都没有。有些时候它很好。

我需要做的是确定第一行是否包装,如果没有包装它。

不幸的是,我不知道从哪里开始这个问题,所以任何帮助,将不胜感激。

回答

3

请尝试使用此代码来包装任何未包含<p>标记的TextNode。

function getTextNodesIn(node, includeWhitespaceNodes) { 
    var textNodes = [], whitespace = /^\s*$/; 

    function getTextNodes(node) { 
     if (node.nodeType == 3) { 
      if (includeWhitespaceNodes || !whitespace.test(node.nodeValue)) { 
       textNodes.push(node); 
      } 
     } else { 
      for (var i = 0, len = node.childNodes.length; i < len; ++i) { 
       getTextNodes(node.childNodes[i]); 
      } 
     } 
    } 

    getTextNodes(node); 
    return textNodes; 
    } 

    var textnodes = getTextNodesIn($("#demo")[0])​​​​; 
    for(var i=0; i < textnodes.length; i++){ 
     if($(textnodes[i]).parent().is("#demo")){ 
      $(textnodes[i]).wrap("<p>"); 
     } 
    }​ 

这里是一个jsfiddle,它显示了这一行动。

PS:TextNode检测部分已经从this answer

+2

做的不错!我添加了一些CSS,使结果更清晰一些:http://jsfiddle.net/reWXX/2/ –

+0

@OllyHodgson太好了:-)我会在答案中更新小提琴网址。 –

0

jQuery是bad at handling text nodes借来的,所以你需要做一些这方面的直接DOM操作。这也使用"trim" function.。它在jsfiddle

var d = $("div")[0]; 

for(var i=0; i<d.childNodes.length; i++) { 
    if(d.childNodes[i].nodeType === 3 && 
     d.childNodes[i].textContent.replace(/^\s+|\s+$/g, "")) { 
     wrapNode(d.childNodes[i]); 
    } 
} 

function wrapNode(node) { 
    $(node).replaceWith("<h1>" + node.textContent + "</h1>"); 
} 
2

试试这个: -

<div class="container"> 
Some text here which is not wrapped in tags 
<p>Some more text which is fine</p> 
<p>Blah blah another good line</p> 
</div>​ 

JS

$(function(){ 
    var $temp = $('<div>'); 
    $('div.container p').each(function(){ 
      $(this).appendTo($temp);    
    });  

    if($.trim($('div.container').html()).length){ 
     var $pTag = $('<p>').html($('.container').html()); 
     $('div.container').html($pTag); 
    } 

    $('div.container').append($temp.html()); 
}); 
​ 

这里是工作示例: -

http://jsfiddle.net/dhMSN/12

3

在这里你去:http://jsfiddle.net/RNt6A/

$('div').wrapInner('<p></p>');​​​​ 
$('div p > p').detach().insertAfter('div p'); 
+0

我喜欢这个选项,但有一个小问题。这并不总是一个p标签。实际上,它几乎可以是任何块级别的标签。有没有选择'div p> blockleveltag'? – Tom

0

跑到类似的需要,并试图采用解决方案@Arash_Milani。解决方案工作,但是当页面也需要进行ajax调用时,我遇到了冲突。

有点挖后,我发现了一个api.jquery.com相当直截了当的解决方案使用.contents()方法:

$('.wrapper').contents().filter(function() { 
 
    return this.nodeType === 3; 
 
}).wrap('<p class="fixed"></p>').end();
p.good { 
 
    color: #09f; 
 
} 
 
p.fixed { 
 
    color: #ff0000; 
 
    text-align: center; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<div class="wrapper"> 
 
    Some plain text not wrapped in any html element. 
 
    <p class="good">This text is properly wrapped in a paragraph element.</p> 
 
</div>

相关问题