我的这段代码受到这个主题的启发:( Adding an onclick event to a table row)。它正常工作,当我点击该行的任何位置时,所有选择输入都将其选定的选项更改为索引1。
不幸的是,我想使用行的第一个td的按钮或链接来完成这项工作...... 就像我在行上有一个链接或按钮,当我点击它时......每个选择选项值都变为索引1
任何人都可以帮助我吗?谢谢
function SetJR() {
var table = document.getElementById("TO2");
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
var createClickHandler =
function (row) {
return function () {
var cell1 = row.getElementsByTagName("td")[1];
var cell2 = row.getElementsByTagName("td")[2];
var cell3 = row.getElementsByTagName("td")[3];
var cell4 = row.getElementsByTagName("td")[4];
var cell5 = row.getElementsByTagName("td")[5];
var cell6 = row.getElementsByTagName("td")[6];
var cell7 = row.getElementsByTagName("td")[7];
var cell1d = cell1.getElementsByTagName("select");
var cell2d = cell2.getElementsByTagName("select");
var cell3d = cell3.getElementsByTagName("select");
var cell4d = cell4.getElementsByTagName("select");
var cell5d = cell5.getElementsByTagName("select");
var cell6d = cell6.getElementsByTagName("select");
var cell7d = cell7.getElementsByTagName("select");
for (b = 0; b < cell1d.length; i++) {
var id = cell1d[b].options;
cell1d[b].selectedIndex = 1;
cell2d[b].selectedIndex = 1;
cell3d[b].selectedIndex = 1;
cell4d[b].selectedIndex = 1;
cell5d[b].selectedIndex = 1;
cell6d[b].selectedIndex = 1;
cell7d[b].selectedIndex = 1;
break;
}
};
};
currentRow.onclick = createClickHandler(currentRow);
}
}
</script>
答案 0 :(得分:1)
function SetJR() {
var createClickHandler = function(row) {
return function() {
var cell1 = row.getElementsByTagName("td")[1];
var cell2 = row.getElementsByTagName("td")[2];
// ...
var cell1d = cell1.getElementsByTagName("select");
var cell2d = cell2.getElementsByTagName("select");
// ...
for (var b = 0; b < cell1d.length; i++) {
cell1d[b].selectedIndex = 1;
cell2d[b].selectedIndex = 1;
// ...
break; // what does this mean? loop will run only once?
}
};
};
var table = document.getElementById("TO2");
for (i = 0; i < table.rows.length; i++) {
var currentRow = table.rows[i];
var button = currentRow.querySelector("td:first-child button");
if (button)
button.onclick = createClickHandler(currentRow);
}
}
SetJR();
<table cellspacing="2" cellpadding="2" border="1" id="TO2">
<tr>
<td><button>Click</button></td>
<td>
<select>
<option>One</option>
<option>Two</option>
<option>Three</option>
</select>
</td>
<td>
<select>
<option>One</option>
<option>Two</option>
<option>Three</option>
</select>
</td>
</tr>
<tr>
<td><button>Click</button></td>
<td>
<select>
<option>One</option>
<option>Two</option>
<option>Three</option>
</select>
</td>
<td>
<select>
<option>One</option>
<option>Two</option>
<option>Three</option>
</select>
</td>
</tr>
</table>
答案 1 :(得分:0)
只需在每行的第一个<button>
中添加<span>
或<td>
元素,并将onclick
属性设置为您的函数。
<tr>
<td>
<button onclick="SetJR()">Button</button> or <span onclick="SetJR()">Span</span>
</td>
...
</tr>