簡體   English   中英

使用jQuery獲取帶有子元素的div文本

[英]Get text of div with child element using jQuery

在以下示例中:

<div id="mainDiv">
  <h1>The <span class="bold">title</span></h1>
  some text
  <p>and again</p>
  <p>another text.</p>
</div>

我正在嘗試將所有文​​本放在一個字符串中。 當我只執行$('#mainDiv').text()它將文本返回為The titlesome textand againanother text返回為The titlesome textand againanother text

在這種情況下,我希望子元素中的單詞之間有空格。 所以我非常接近地做:

if ($('#mainDiv').find("*").length >= 1) {
  $('#mainDiv').find("*").each(function () {
    sFullText = sFullText + $(this).text().trim().replace(/\s\s+/g, ' ') + ' ';
  });
}

現在的結果是: The titlesome textand again another text

因此,當所有文本都在子元素中時有效,但是如果某些文本在mainDiv中則mainDiv (頁面及其內容是動態的,所以我不知道mainDiv有哪些特定元素)

從此處使用jQuery插件: http : //viralpatel.net/blogs/jquery-get-text-element-without-child-element/

jQuery.fn.justtext = function() {
    return $(this)  .clone()
            .children()
            .remove()
            .end()
            .text();
};

// ...

var sFullText = $('#mainDiv').justtext();
if ($('#mainDiv').find("*").length >= 1) {
    $('#mainDiv').find("*").each(function () {
        sFullText = sFullText + ' ' + $(this).text().trim().replace(/\s\s+/g, ' ');
    });
}

您可以嘗試使用自己的代碼,但可以使用正則表達式將一個或多個空格字符\\s (檢查此定義 )替換為一個空格' ' 像這樣:

$("#mainDiv").text().replace(/\s+/g, ' ')

您可以在jsfiddle上查看示例。

我相信當您放平html時,您的問題就存在了:

<div id="mainDiv" style="display:none;"><h1>The <span class="bold">title</span></h1>some text<p>and again</p><p>another text.</p></div>

<div id="result"></div>

$("#result").html($("#mainDiv").text());

暫無
暫無

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

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