簡體   English   中英

我如何存儲所有內容<p>使用 javascript 和 jquery 在數組中標記?</p>

[英]How i can store all content from <p> tag in array using javascript and jquery?

以下是我正在處理的代碼

 var all=$('p').text(); var len_all=$('p').length; var all_array=[]; for (var i=0; i < len_all; i++) { console.log(all); all_array.push(all); } console.log(all_array);
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <p>I am out</p> <p>I am in</p>

我想要var all_array=[];中的所有<p>標記內容我在控制台中關注 output:

(2) ['我出我入','我出我入']

預期是:

['我出去了','我進來了']

那是因為$('p').text(); 將獲得所有p元素的text

您可以使用一行vanilla javascript來實現您的目標,通過querySelectorAllmap獲取所有p元素來獲取每個元素textContent

 <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> </head> <body> <p>I am out</p> <p>I am in</p> <script> let all_array = [...document.querySelectorAll('p')].map(el => el.textContent); console.log(all_array) </script> </body> </html>

您在這里將所有值都視為一個大值:

var all=$('p').text();

然后反復將相同的值推送到數組中:

all_array.push(all);

相反,循環遍歷<p>元素並將每個值推送到數組中:

 var pElements = $('p'); var result = []; pElements.each(function (i, el) { result.push($(el).text()); }); console.log(result);
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <p>I am out</p> <p>I am in</p>

嘗試這個:

var all=$('p');
var len_all=$('p').length;
var all_array=[];
for (var i=0; i < len_all; i++) {
  console.log(all[i].text());
  all_array.push(all[i].text());
}
console.log(all_array)

或者

var all=$('p');
var len_all=$('p').length;
var all_array=[];
for (var i=0; i < len_all; i++) {
  console.log($(all[i]).text());
  all_array.push($(all[i]).text());
}
console.log(all_array)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM