javascript - 计算标签并输出变量

标签 javascript jquery html

<html>
<head>

<script>



$(document).ready(function () { 

var items = document.getElementByTag('section').length;

alert(items);       

 });



</script>
</head>
       <body>
       <section>
 This should be counted
 </section>
 <section>
 This should be counted
 </section>
 <section>
 This should be counted
    </section>
     <section>
     This should be counted
     </section>
     <section>
     This should be counted
     </section>

  There are currently <b id='test'></b> alerts


</body>

我希望能够在加载页面时计算代码中的节元素数量。我希望它插入到 <b> 的位置是。但是我无法让它计算元素。我究竟做错了什么?

最佳答案

首先,您的页面中没有包含 jQuery 库来进行以下工作:

$(document).ready(function() { ... });

接下来,如果您考虑使用纯 JavaScript,那么您应该考虑没有方法 getElementByTag ,有一个方法 getElementsByTagName (遵循 s 之后 Element )。

最后,您必须在页面中包含 jQuery 并使用它:

$(document).ready(function() {
    $('#test').text($('section').length);
});

或者把你的<script>结束前的标签 </body>标记并编写如下内容:

var sections = document.getElementsByTagName('section'),
    text = document.createTextNode(sections.length);

document.getElementById('test').appendChild(text);

关于javascript - 计算标签并输出变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22204694/

相关文章:

javascript - 从输入修改数组然后返回输出

javascript - react axios 形式

php - Jquery 提交单选按钮无需重新加载和

jquery - 如何使用 HTML 和 CSS 为输入字段的背景图像添加工具提示

javascript - 在 HTML 页面之间共享数据

javascript - 如何获取 x 和 y 值来检测 html5 Canvas 中两个图像之间的碰撞?

javascript - Knockout.js 不更新可观察值

javascript - 如何在MVC4的UI中使用jQuery创建DataTable?

javascript - 递归添加点击事件处理程序

当 UserControl 使用 Ajax 加载时,Javascript 代码不起作用