gpt4 book ai didi

javascript - 如何访问 HTML 表中元素的属性?

转载 作者:行者123 更新时间:2023-12-02 16:59:26 25 4
gpt4 key购买 nike

我正在尝试获取除 TR 和 TD 之外的 html 元素并获取它们的 ID 属性。奇怪的是,当我尝试使用警报功能通过 document.getElementById("someId") 获取元素时,会出现一些内容。但是当我捕获元素并使用对 id 的直接调用时,它告诉 undefined。

这是我在 JSFiddle 中的代码 http://jsfiddle.net/ss7ykqyh/

示例 HTML:

    <tr>
<td> <input id="button1" /> </td>
<td> <input id="button2" /> </td>
</tr>

<tr>
<td> <input id="button3" /> </td>
<td> <input id="button4" /> </td>
</tr>

</table>


<input value="clone me!" type="button" id="btnCloneMe" onclick="myFunction()" />

我的脚本:

function myFunction() {

var table = document.getElementById("table1");
var rows = table.rows;


for(var i = 0; i < rows.length; i++){
var noOfCells = rows[i].cells.length;
alert("no of cells: " + noOfCells);

for(var j = 0; j < noOfCells; j++){

var cell = rows[i].cells[j].innerHTML;
alert("inside cell: " + cell.id);

var element = document.getElementById("button1");
alert(element.id);

}

}



}

这是一种方法,我也在想是否有更好的方法来捕获除 TD 和 TR 之外的所有 html 元素

此外,仅发布 JSFiddle url 是否违规,或者我是否需要直接在查询中发布代码?谢谢并致以诚挚的问候!

最佳答案

innerHTML 返回一个字符串,而不是一个对象,因此它没有 ID 属性

var cell = rows[i].cells[j].innerHTML;
alert("inside cell: " + cell.id);

看看cell如何是一个字符串

您可以删除 innerHTML 调用,但单元格没有 ID?

var cell = rows[i].cells[j]; // returns empty string ?

我猜您想要按钮的 ID,然后您必须先找到它们,一种方法是使用 querySelector

var cell = rows[i].cells[j].querySelector('input');

FIDDLE

关于javascript - 如何访问 HTML 表中元素的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25889319/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com