热门关键字:
jquery > jquery教程 > jquery教程 > 如何使用jQuery获取div中的元素数量

如何使用jQuery获取div中的元素数量

407
作者:管理员
发布时间:2021/2/7 15:08:48
评论数:0
转载请自觉注明原文:http://www.jq-school.com/Show.aspx?id=3938
答案:使用jQuery.length属性
您可以简单地使用jQuery.length属性来查找DIV元素或任何其他元素中的元素数量。以下示例将警告<div>具有.content文档就绪类事件的元素中的段落数。


例试试这个代码»
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Get Number of Paragraphs in a Div</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
    $(document).ready(function(){
        var matched = $(".content p");
        alert("Number of paragraphs in content div = " + matched.length);
    });
</script>  
</head> 
<body>
    <div class="content">
        <h1>This is a heading</h1>
        <p>This is a paragraph.</p>
        <p>This is another paragraph.</p>
        <div>This is just a block of text.</div>
        <p>This is one more paragraph.</p>
    </div>
</body>
</html>
但是,如果要获取所有子元素的数量而不管它们的类型如何,只需使用通用选择器,即星号(*),如下所示:


例试试这个代码»
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Get Number of Child Elements in a Div</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
    $(document).ready(function(){
        var matched = $(".content *");
        alert("Number of elements in content div = " + matched.length);
    });
</script>  




如果您觉得本文的内容对您的学习有所帮助:支付鼓励



关键字:在线预览PDF文件
友荐云推荐