显示为0长度的Javascript HTML集合 [英] Javascript HTML collection showing as 0 length
本文介绍了显示为0长度的Javascript HTML集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
var eval_table = document.getElementsByClassName("evaluation_table");
console.log(eval_table);
显示为:
[item: function, namedItem: function]0:
table.widefat.fixed.evaluation_table
length: 1
__proto__: HTMLCollection
但是,当我尝试获取长度为 eval_table
的 eval_table.length
时,它返回的值为 0
.我以前使用过这种方法,以前没有这种方法的问题.我要达到的目标有什么问题吗?
However, when I try to get a length of eval_table
, eval_table.length
, it returns a value of 0
. I've used this approach before, had no issues with this approach before. Is there anything wrong with what I'm trying to achieve above?
推荐答案
这是因为在将元素呈现到DOM之前,您的JS正在运行.我敢打赌,您正在运行的脚本会在html的< body>
之前加载.您有两种选择:
This is because your JS is running before the elements are rendered to the DOM. I bet the script you have running is loaded before the <body>
of your html. You have two options:
- 将自执行的
< script>
添加为< body>
标记中的最后一个内容,或 - 包装您的函数,以便它在执行之前等待DOM加载.您可以使用以下任一方法执行此操作:
- jQuery的
$(document).ready
或 - 如果您未运行jQuery:
document.addEventListener("DOMContentLoaded",function(e){//做事})
- jQuery的
- Add the self-executing
<script>
as the last thing in your<body>
tag or; - Wrap your function so that it waits for the DOM to be loaded before executing. You can do this with either:
- jQuery's
$(document).ready
or - if you're not running jQuery:
document.addEventListener("DOMContentLoaded", function(e) {// do stuff })
- jQuery's
下面的代码示例:
<html>
<head></head>
<script>
document.addEventListener("DOMContentLoaded", function(e) {
var eval_table = document.getElementsByClassName('evaluation_table');
console.log(eval_table, eval_table.length);
});
</script>
<body>
<div class="evaluation_table"></div>
<div class="evaluation_table"></div>
<div class="evaluation_table"></div>
<div class="evaluation_table"></div>
</body>
</html>
这篇关于显示为0长度的Javascript HTML集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文