[英]Get text of div with child element using jQuery
In the following example: 在以下示例中:
<div id="mainDiv">
<h1>The <span class="bold">title</span></h1>
some text
<p>and again</p>
<p>another text.</p>
</div>
I'm trying to get all the text in one string. 我正在尝试将所有文本放在一个字符串中。 When I just do
$('#mainDiv').text()
it returns the text as The titlesome textand againanother text
. 当我只执行
$('#mainDiv').text()
它将文本返回为The titlesome textand againanother text
返回为The titlesome textand againanother text
。
In this case I would like to have spaces between the words in child elements. 在这种情况下,我希望子元素中的单词之间有空格。 So I came very close doing:
所以我非常接近地做:
if ($('#mainDiv').find("*").length >= 1) {
$('#mainDiv').find("*").each(function () {
sFullText = sFullText + $(this).text().trim().replace(/\s\s+/g, ' ') + ' ';
});
}
The result now is: The titlesome textand again another text
. 现在的结果是:
The titlesome textand again another text
。
So this works when all text is in child elements, but not if some text is in the mainDiv
. 因此,当所有文本都在子元素中时有效,但是如果某些文本在
mainDiv
中则mainDiv
。 (the page and it's content is dynamic so I don't know what specific elements are in mainDiv
) (页面及其内容是动态的,所以我不知道
mainDiv
有哪些特定元素)
Using a jQuery plugin from here: http://viralpatel.net/blogs/jquery-get-text-element-without-child-element/ 从此处使用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, ' ');
});
}
You can try your own code, but using a regex to replace one or multiple whitespace characters \\s
(check this definition ) with a single space one ' '
. 您可以尝试使用自己的代码,但可以使用正则表达式将一个或多个空格字符
\\s
(检查此定义 )替换为一个空格' '
。 Something like this: 像这样:
$("#mainDiv").text().replace(/\s+/g, ' ')
You can check the example on this jsfiddle . 您可以在jsfiddle上查看示例。
I believe your problem exists when you flatten down your html: 我相信当您放平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.