javascript - 嵌套的 GetElementsByClassName 在 window.onload 函数内部返回未定义的错误

标签 javascript

我的页面上有一个表格,它看起来像这样:

<body>
<table class="table table-bordered">
    <thead>
    <tr>
        <th>#</th>
        <th>Product name</th>
        <th>Product description</th>
        <th>Price</th>
        <th>Details</th>
    </tr>
    </thead>
    <tbody>


    <tr style="height: 50px;">
        <td>1</td>
        <td>Mug</td>
        <td>Perfect for drinking stuff</td>
        <td>41</td>
        <td><a href="/products/detail?id=1"><i class="glyphicon glyphicon-info-sign"></i></a></td>
    </tr>

    etc....

</body>

我正在尝试编写一些 javascript 代码来访问“a”标记和 href 属性。 我不能给它一个 id 来轻松访问它所以我试图通过以下方式访问它:

var btn = document.getElementsByTagName("tbody")[0].getElementsByTagName("a")[0];
console.log(btn.href);

但是,我收到以下错误:btn 未定义。

如果我尝试打印出 tbody 元素,它会返回一个对象,所以我不确定为什么这对它的子标签不起作用。

我应该注意到这个 JavaScript 是在 window.onload 函数中执行的。

最佳答案

对于这种特殊情况,最好使用 document.querySelectorAll() :

var btn = document.querySelectorAll("tbody a")[0];
console.log(btn.href);

示例:

var btn = document.querySelectorAll("tbody a")[0];
console.log(btn.href);
<table class="table table-bordered">
<thead>
    <tr>
        <th>#</th>
        <th>Product name</th>
        <th>Product description</th>
        <th>Price</th>
        <th>Details</th>
    </tr>
</thead>
<tbody>
    <tr style="height: 50px;">
        <td>1</td>
        <td>Mug</td>
        <td>Perfect for drinking stuff</td>
        <td>41</td>
        <td><a href="/products/detail?id=1"><i class="glyphicon glyphicon-info-sign"></i></a></td>
    </tr>
</tbody>
</table>

关于javascript - 嵌套的 GetElementsByClassName 在 window.onload 函数内部返回未定义的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54663096/

相关文章:

javascript - 使用javascript将谷歌地图时区转换为GMT字符串

javascript - jquery onkey左右滑动无法正常工作?

javascript - 将一个变量替换为另一个变量

javascript - p5.j​​s – keyPressed 函数和改变 y 坐标的困难

javascript - 无法在 IE 的特定行上设置断点

javascript - 响应式卡片布局 CSS 设计未修复

javascript - Bootstrap 模式中的 Summer Note 问题

javascript - ./src/index.scss (./node_modules/css-loader/dist/cjs.js??ref--6-oneOf-5-1!./node_modules/postcss-loader/src??postcss!./node_modules/

javascript - HTML 表单输入字段为空时 Google Apps 脚本出错

javascript - 从另一个ajax函数获取json编码数据