jQuery – 将所有未包装的文本包装在p标签中

我有一种情况,以下代码被写入我的页面。

Some text here which is not wrapped in tags

Some more text which is fine

Blah blah another good line

在这种情况下,它似乎总是第一行没有包装在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("

"); } }​

这是一个jsfiddle ,显示了这一点。

PS:TextNode检测部分已经从这个答案借来

你去的地方: http : //jsfiddle.net/RNt6A/

 $('div').wrapInner('

');​​​​ $('div p > p').detach().insertAfter('div p');

试试这个 :-

 
Some text here which is not wrapped in tags

Some more text which is fine

Blah blah another good line

JS

  $(function(){ var $temp = $('
'); $('div.container p').each(function(){ $(this).appendTo($temp); }); if($.trim( $('div.container').html() ).length){ var $pTag = $('

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

以下是工作示例: –

http://jsfiddle.net/dhMSN/12

jQuery 处理文本节点很糟糕 ,所以你需要对它进行一些直接的DOM操作。 这也使用“修剪”function。 。 它在jsfiddle 。

 var d = $("div")[0]; for(var i=0; i" + node.textContent + ""); } 

遇到类似的需求并尝试使用解决方案@Arash_Milani。 解决方案有效,但是当页面还需要进行ajax调用时,我遇到了冲突。

经过一番挖掘,我使用.contents()方法在api.jquery.com上找到了一个相当直接的解决方案:

 $('.wrapper').contents().filter(function() { return this.nodeType === 3; }).wrap('

').end();
 p.good { color: #09f; } p.fixed { color: #ff0000; text-align: center; } 
  
Some plain text not wrapped in any html element.

This text is properly wrapped in a paragraph element.