计数标签和输出变量

时间:2014-03-05 17:19:58

标签: 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>所在的位置。但是,我无法计算元素。我究竟做错了什么?

4 个答案:

答案 0 :(得分:3)

首先,您不要在页面中包含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);

答案 1 :(得分:0)

您可以使用jquery选择器。

$(document).ready(function(){

$("#test").html($("section").length());
});

答案 2 :(得分:0)

我认为VisioN的意思是

&#34;首先,您没有在您的页面中包含jQuery库[这是必需的]以进行以下工作:&#34;

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

答案 3 :(得分:0)

var ct = document.querySelectorAll('section').length;

document.querySelector('#test').innerHTML = ct;