[英]How to fix undefined divs in javascript?
例如我输入
var x1 = document.getElementsByClassName('js-ticket-count');
未定义 & HtmlCollection !
x1 = document.getElementsByClassName('js-ticket-count')[0];
它返回未定义? 为什么?
Html 代码:
<div class='js-ticket-count'>
<p id='style-1'>test<p>
<p id='style-1'>test<p>
<p id='style-1'>test<p>
<p id='style-1'>test<p>
<p id='style-1'>test<p>
<div>
**More Html Stuff Here**
</div>
</div>
尝试将您的 JS 放在 onload 侦听器中。 否则,您的 JS 很可能在元素加载到 DOM 之前正在运行。
window.onload = function(){
alert(document.getElementsByClassName('js-ticket-count')[0]);
}
您看到的HtmlCollection
基本上是一个元素数组,因为可能有多个元素具有某个 class 名称。 您使用[0]
返回第一个元素。
DOMContentLoaded
事件来确保文档是这样加载的:document.addEventListener("DOMContentLoaded", function(){
var x1 = document.getElementsByClassName('js-ticket-count');
x1 = document.getElementsByClassName('js-ticket-count')[0];
console.log(x1)
})
load
事件:window.addEventListener("load", function(){
var x1 = document.getElementsByClassName('js-ticket-count');
x1 = document.getElementsByClassName('js-ticket-count')[0];
console.log(x1)
})
script
标签在body
标签之前关闭,以确保每个元素都已加载。如果您使用的是外部 JS 文件,则可以将其添加到 body 元素的末尾。 因此,您的 JS 文件将在加载完所有 HTML 元素后加载。 这样,JS就可以读取到HTML元素了。 像这样的东西:
<body>
<div class='js-ticket-count'>
<p id='style-1'>test<p>
<p id='style-1'>test<p>
<p id='style-1'>test<p>
<p id='style-1'>test<p>
<p id='style-1'>test<p>
<div>
**More Html Stuff Here**
</div></div>
<script srs="externalJSlink.js"></script>
</body>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.