在jQuery上创建带有标签的数组



我想从正文中获取所有"p"并创建一个数组,然后使用此数组打印每个"p"的文本内容,如何存档?非常新手的问题,但我被困住了。

谢谢。

在 jquery 中尝试使用 .map()

var result = $("body").find("p").map(function() {
   return $(this).text();
}).get();
 console.log(result);

小提琴

有很多方法可以做到这一点,使用纯JavaScript或jQuery:

JavaScript:

var p = document.getElementsByTagName('p'); // Get all paragraphs (it's fastest way by using getElementsByTagName)
var pTexts = []; // Define an array which will contain text from paragraphs

// Loop through paragraphs array
for (var i = 0, l = p.length; i < l; i++) {
    pTexts.push(p[i].textContent); // add text to the array
}

循环 jQuery 方式:

$.each(p, function(i, el) {
    pTexts.push(el.textContent);
    // or using jQuery text(), pretty much the same as above
    // pTexts.push( $(el).text() );
});

最新更新