要获取HTML表格第一列的值,可以使用JavaScript结合DOM操作来实现。以下是一个简单的示例,展示了如何获取并打印出表格第一列的所有值:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Table Example</title>
</head>
<body>
<table id="myTable" border="1">
<tr>
<td>Row1 Cell1</td>
<td>Row1 Cell2</td>
<td>Row1 Cell3</td>
</tr>
<tr>
<td>Row2 Cell1</td>
<td>Row2 Cell2</td>
<td>Row2 Cell3</td>
</tr>
<tr>
<td>Row3 Cell1</td>
<td>Row3 Cell2</td>
<td>Row3 Cell3</td>
</tr>
</table>
<button onclick="getFirstColumnValues()">Get First Column Values</button>
<script src="script.js"></script>
</body>
</html>
function getFirstColumnValues() {
const table = document.getElementById('myTable');
const rows = table.getElementsByTagName('tr');
const firstColumnValues = [];
for (let i = 0; i < rows.length; i++) {
const cells = rows[i].getElementsByTagName('td');
if (cells.length > 0) {
firstColumnValues.push(cells[0].innerText);
}
}
console.log(firstColumnValues);
}
myTable
,包含三行和三列。getFirstColumnValues
函数通过document.getElementById
获取表格元素。getElementsByTagName('tr')
获取所有行。getElementsByTagName('td')
获取该行的所有单元格。firstColumnValues
数组中。querySelectorAll
)来精确选择目标元素。通过上述方法,可以有效地获取HTML表格第一列的值,并应用于各种实际场景中。
领取专属 10元无门槛券
手把手带您无忧上云