我正在使用cheerio.js 來決議一些HTML 檔案,但我面臨著某些問題。
問題是我使用的 HTML 檔案包含以下代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>
</title>
</head>
<body>
<p>Text 1</p>
<p>Text 2</p>
</body>
</html>
現在,我還有一個 javascript 專案陣列,如下所示:
var items = ["<h2>orange</h2>", "<h2>mango</h2>"];
我想要做的只是用 items 陣列中的相應專案替換每個 P 標簽,即:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>
</title>
</head>
<body>
<h2>orange</h2>
<h2>mango</h2>
</body>
</html>
到目前為止我嘗試過的:
var selections = $("p");
for ( let index = 0; index < selections.length; index ) {
selections[index].replaceWith(items[index])
}
但它說函式 replaceWith() 無效
uj5u.com熱心網友回復:
解決方案:
使用 each 方法,可以輕松處理特定元素
解決上述問題:
var items = ["<h2>orange</h2>", "<h2>mango</h2>"];
$("p").each((index, element) => $(element).replaceWith(items[index]))
基本上, each 方法將呼叫一個回呼函式,其中 element 是該特定元素的選擇器,而 index 是該專案在該選擇中的位置。
更多參考,請查看:https : //cheerio.js.org/classes/Cheerio.html#each
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/392120.html
標籤:javascript html 节点.js 循环 啦啦队
