簡體   English   中英

jQuery - 將所有未包裝的文本包裝在p標簽中

[英]jQuery - wrap all unwrapped text in p tags

我有一種情況,以下代碼被寫入我的頁面。

<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標簽中,這可能使解決方案變得更容易,盡管並非每次都如此。 有時候很好。

我需要做的是確定第一行是否被包裹,如果沒有,則將其包裹起來。

不幸的是我不知道從哪里開始這個問題所以任何幫助將不勝感激。

嘗試使用此代碼來包裝未包含<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檢測部分已經從這個答案借來

你去吧: http//jsfiddle.net/RNt6A/

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

試試這個 :-

<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

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>");
}

遇到類似的需求並嘗試使用解決方案@Arash_Milani。 解決方案有效,但是當頁面也需要進行ajax調用時,我遇到了沖突。

經過一番挖掘后,我使用.contents()方法在api.jquery.com上找到了一個相當簡單的解決方案:

 $('.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> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM