首页 > 解决方案 > 如何修复javascript中未定义的div?

问题描述

例如我输入

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>

标签: javascripthtml

解决方案


尝试将您的 JS 放在 onload 侦听器中。否则,您的 JS 很可能在元素加载到 DOM 之前正在运行。

window.onload = function(){
    alert(document.getElementsByClassName('js-ticket-count')[0]);
}

HtmlCollection您看到的基本上是一个元素数组,因为可能有多个元素具有某个类名。您将使用 . 返回第一个元素[0]


推荐阅读