javascript - 如何修复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>
解决方案
尝试将您的 JS 放在 onload 侦听器中。否则,您的 JS 很可能在元素加载到 DOM 之前正在运行。
window.onload = function(){
alert(document.getElementsByClassName('js-ticket-count')[0]);
}
HtmlCollection
您看到的基本上是一个元素数组,因为可能有多个元素具有某个类名。您将使用 . 返回第一个元素[0]
。
推荐阅读
- tsql - Power Automate - 执行存储过程 (V2) - 始终返回 HTTP 错误 400
- javascript - 尝试使用 jquery 和会话 cookie 创建一个记住我的功能,但应用程序在再次运行时甚至不会加载
- r - 如何使用“是”或“否”重命名逻辑值(TRUE 或 FALSE)并将 distinct() 应用于 FALSE 值
- javascript - 使 chrome 扩展能够查询浏览器页面的窗口
- macos - Spotlight 货币转换器未更新
- dafny - 断言和集合基数
- html - HTML5画布可动线
- swift - CGContext.draw(), CGContext.makeImage() 给我双倍的预期分辨率
- android-studio - 在 Android Studio 中配置导入顺序?
- javascript - 如何在client.js中访问登录表单的输入标签值(名称)