我有一个HTML表格,单元格中有一些下拉列表。我想访问我的下拉选项,就像我在下面尝试的那样。我怎样才能做到这一点?我的JavaScript似乎不起作用。
<table id = "xy">
<tr>
<td>
<select>
<option>--Please Select--</option>
<option>value 1</option>
<option>value 2</option>
<option>value 3</option>
</select>
</td>
</tr>
<tr>
<td>
<select>
<option>--Please Select--</option>
<option>value 1</option>
<option>value 2</option>
<option>value 3</option>
</select>
</td>
</tr>
</table>
<script type="text/javascript">
...
var table = document.getElementById("xy");
for (var i = 0, row; row = table.rows[i]; i++) {
alert(row.cells[0].innerHTML.options[0].value);
alert(row.cells[1].innerHTML.options[0].value);
}
...
</script>
答案 0 :(得分:0)
获取表格中的所有tr
元素:
var selects = document.querySelectorAll('#xy tr');
然后阅读每行value
的{{1}}:
select
示例:强>
var rows = document.querySelectorAll('#xy tr');
for (var i = 0; i < rows.length; i++) { //iterate over rows
var selects = rows[i].querySelectorAll('select');
for (var j = 0; j < selects.length; j++) { //iterate over selects in a row
console.log('Row number: ' + i);
console.log(selects[j].value);
}
}
function readValues() {
var rows = document.querySelectorAll('#xy tr');
for (var i = 0; i < rows.length; i++) {
var selects = rows[i].querySelectorAll('select');
for (var j = 0; j < selects.length; j++) {
console.log('Row number: ' + i);
console.log(selects[j].value);
}
}
}