如何使用jquery获取每个文件中p标记的数量

How to get the number of p tag in each file using jquery

本文关键字:文件 jquery 何使用 获取      更新时间:2023-09-26

我正在像一样将html文件加载到div

var j1 = $('<div class = "cl1">').load('components/1.html');
                var j2 = $('<div class = "cl2">').load('components/2.html');
                var j3 = $('<div class = "cl3">').load('components/3.html');                

            $("#search_content").append(j1);
            $("#search_content").append(j2);
            $("#search_content").append(j3);

我想得到每个文件中p标记的计数。提前谢谢。

您可以在包含文档的每个元素中搜索p标记。在您给定的片段中:

var j1 = $('<div class = "cl1">').load('components/1.html', function() {//after content loaded
    var ptags = j1.find("p").length
});

更新:如果你想同时使用这三个,他应该使用promise-请参阅这篇文章,了解如何使用promise 加载内容

所以您需要为每个文件计数?加载一个文件,计算段落数,再加载另一个,然后再计数?最简单的方法是:

function count_pars(){
var n=0;
$('p').each(
function(){
n=n+1;
})
//do stuff 
}

并像这样使用:

$("#search_content").append(j1);
count_pars();