簡體   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