5

我遇到以下代码被写入我的页面的情况。

<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 标签中,这可能会使解决方案更容易,尽管并非每次都如此。有时它很好。

我需要做的是确定第一行是否被换行,如果没有,则换行。

不幸的是,我不确定从哪里开始解决这个问题,因此我们将不胜感激。

4

5 回答 5

4

给你:http: //jsfiddle.net/RNt6A/

$('div').wrapInner('<p></p>');​​​​
$('div p > p').detach().insertAfter('div p');
于 2012-12-12T10:12:00.153 回答
4

尝试使用此代码来包装任何未用<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

于 2012-12-12T09:37:59.283 回答
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

于 2012-12-12T10:05:00.233 回答
0

jQuery不擅长处理文本节点,因此您需要对此进行一些直接的 DOM 操作。这也使用了“修剪”功能。. 它在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>");
}
于 2012-12-12T09:57:11.720 回答
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>

于 2017-01-06T07:11:52.647 回答