简体   繁体   English

如何修复 javascript 中未定义的 div?

[英]How to fix undefined divs in javascript?

For Example I Type例如我输入

var x1 = document.getElementsByClassName('js-ticket-count');

undefined & HtmlCollection !未定义 & HtmlCollection !

x1 = document.getElementsByClassName('js-ticket-count')[0];

it return as undefined?它返回未定义? why?为什么?

Html Code: 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>

Try putting your JS inside an onload listener.尝试将您的 JS 放在 onload 侦听器中。 Otherwise it's likely your JS is running before the elements have loaded into the DOM.否则,您的 JS 很可能在元素加载到 DOM 之前正在运行。

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

The HtmlCollection you're seeing is basically an array of elements, as there may be multiple elements with a certain class name.您看到的HtmlCollection基本上是一个元素数组,因为可能有多个元素具有某个 class 名称。 You're returning the first element with [0] .您使用[0]返回第一个元素。

  • you can use DOMContentLoaded event to make sure that document is loaded like this:您可以使用DOMContentLoaded事件来确保文档是这样加载的:
document.addEventListener("DOMContentLoaded", function(){
    var x1 = document.getElementsByClassName('js-ticket-count');
        x1 = document.getElementsByClassName('js-ticket-count')[0];
    console.log(x1)
})
  • you can also use load event on window object like this:您还可以像这样在 window object 上使用load事件:
window.addEventListener("load", function(){
    var x1 = document.getElementsByClassName('js-ticket-count');
        x1 = document.getElementsByClassName('js-ticket-count')[0];
    console.log(x1)
})
  • also make sure that your script tag on before of body tag close to make sure that the every element is loaded.还要确保您的script标签在body标签之前关闭,以确保每个元素都已加载。

If in case you are using the external JS file then maybe add it at the end of the body element.如果您使用的是外部 JS 文件,则可以将其添加到 body 元素的末尾。 So your JS file will load after all the HTML elements have been loaded.因此,您的 JS 文件将在加载完所有 HTML 元素后加载。 In this way, JS can read the HTML element.这样,JS就可以读取到HTML元素了。 Something like this:像这样的东西:

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM