我无法理解如何抓取表格行单元格中的href属性。当我尝试这样做时,似乎第二个循环对选定的TR
元素不起作用
function asd(){
this.container = document.getElementsByClassName("cart-contents")[0];
if (!this.container){
return false;
}
this.itemsContainer =
this.container.getElementsByClassName("minicart-table")[0];
this.itemsTable = this.itemsContainer.getElementsByClassName("views-table")[0];
this.cartDetails = [];
for (var i = 0, row; row = this.itemsTable.rows[i]; i++) {
for (var j = 0, col; col = row.cells[j]; j++) {
console.log(col[0].getElementsByTagName("a")[0].getAttribute("href"));
}
console.log('________________');
}
}
asd();

<div class="cart-contents">
<div class="minicart-table">
<table class="views-table">
<tbody>
<tr>
<td class="views-field-field-product-image"><a href="url">text</a></td>
<td class="tg-yw4l"></td>
</tr>
</tbody>
</table>
</div>
</div>
&#13;
答案 0 :(得分:1)
使用querySelector()
。使用safe。例如:
var anchor = document.querySelector(".cart-contents a:first-child");
console.log(anchor.getAttribute("href"));
&#13;
<div class="cart-contents">
<div class="minicart-table">
<table class="views-table">
<tbody>
<tr>
<td class="views-field-field-product-image"><a href="url">text</a></td>
<td class="tg-yw4l"></td>
</tr>
</tbody>
</table>
</div>
</div>
&#13;
此外,以下是修复代码的方法:
for (var i = 0, row; row = this.itemsTable.rows; i++) {
for (var j = 0, col; col = row[i].cells; j++) {
console.log(col[j].getElementsByTagName("a")[0].getAttribute("href"));
}
}
答案 1 :(得分:1)
使用col
代替col[0]
function asd(){
this.container = document.getElementsByClassName("cart-contents")[0];
if (!this.container){
return false;
}
this.itemsContainer =
this.container.getElementsByClassName("minicart-table")[0];
this.itemsTable = this.itemsContainer.getElementsByClassName("views-table")[0];
this.cartDetails = [];
for (var i = 0, row; row = this.itemsTable.rows[i]; i++) {
// only the first column
col = row.cells[0];
var anchor = col.getElementsByTagName("a")[0];
if (anchor !== undefined) {
console.log(anchor.getAttribute("href"));
}
console.log('________________');
}
}
asd();
<div class="cart-contents">
<div class="minicart-table">
<table class="views-table">
<tbody>
<tr>
<td class="views-field-field-product-image"><a href="url">text</a></td>
<td class="tg-yw4l"></td>
</tr>
</tbody>
</table>
</div>
</div>