繁体   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