繁体   English   中英

如何将 text() 返回的内容存储在 jquery 中?

[英]How do I store the content returned by text() in jquery?

我一直在尝试从 HTML 文档中提取全文内容进行计算,我能够在 jquery 中找到解决方案,但它是相当部分的......输出与以下代码的预期一致:

$(document).ready(function(){ 
    console.log($("*").text())
})

这就是我所说的输出。 我想将控制台中的内容存储在一个变量中。 当我尝试做类似的事情时

var words = []
$(document).ready(function(){ 
    words.push($("*").text())
})
console.log(words)

它返回undefined 我开始知道这是因为回调的异步。 我如何处理这个问题。 提前致谢。

考虑您的 Selector,我认为您的范围抓取了太多元素。 看看以下内容。

 $(function() { var words = []; $("body").children().not("script").each(function(i, el) { words.push($(el).text().trim()); }); console.log(words); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <h1>Introduction</h1> <p>This is a paragraph. </p> <div class="footer">02.12.2020</div>

这将迭代 Body 标记的所有子元素。 它将读取每个元素的文本并将其输入到数组中它自己的条目中。 你的结果是这样的:

[
  "Introduction",
  "This is a paragraph.",
  "02.12.2020"
]

一种方法是获取正文中的所有元素,遍历它们以获取它们的文本内容。 使用 jQuery,它看起来像这样:

 $(document).ready(function() { let content = [] $('body * :not(script)').each((i, el) => { content.push($(el).text()) }) console.log(content) })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <aside> <h1>JS Documentation</h1> <ul> <li>Introduction</li> <li>What you should already know</li> </ul> </aside> <main> <h2>Introduction</h2> <p>JavaScript is a cross platform...</p> </main>

注意:: :not(script)选择器会在文档的<body>中省略任何<script>标签(如果存在)。

提示:如果您需要摆脱换行符空白,您可以使用以下方法:

text().trim().replace(/\r?\n|\r/g, '')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM