<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/