下面是来自 innerhtml 的代码,显示在 GridView 中。当从同一行选中一个复选框时,我需要取消选中其他复选框:
for(var i = 0; i < optionsArray.length; i++){
HTML += "<tr>"+
"<td class=tdhead verificationTable width=40% align=left>"+optionsArray[i]+"</td>"+
"<td width=20%>"+
"<input type=checkbox name=text value="+optionsArray[i]+" id="+i+" onclick=checkbox(this);></input>"+
"</td>"+
"<td width=20%>"+
"<input type=checkbox name=text value=somevalue id="+i+"/>"+
"</td>"+
"</tr>";
}
function checkbox(obj){
var id = obj.id;
if (obj.checked == true)
{
document.getElementById(what/how to mention other id here).checked = false;
}
}
我如何在 javascript 中获取 document.getElementById 的其他复选框 ID,因为它需要一个字符串? 请帮忙!
最佳答案
一些事情:
- id 不能以整数开头。所以你需要在它之前附加一些东西:
id_
- ID 必须是唯一的。您正在为多个复选框分配相同的 ID。
您可以将类与 querySelectorAll
结合使用。
HTML = "";
optionsArray = [1, 2, 3, 4, 5, 6];
for (var i = 0; i < optionsArray.length; i++) {
HTML += "<tr>" +
"<td class=tdhead verificationTable width=40% align=left>" + optionsArray[i] + "</td>" +
"<td width=20%>" +
"<input type=checkbox name=text value=" + optionsArray[i] + " id='id_" + i + "' onclick=checkbox(this);></input>" +
"</td>" +
"<td width=20%>" +
"<input type=checkbox name=text value=somevalue class='row_" + i + "' />" +
"</td>" +
"</tr>";
}
document.querySelector("table").innerHTML = HTML;
function checkbox(obj) {
var boolValue;
obj.checked == true ? boolValue = true : boolValue = false;
Array.prototype.map.call(document.querySelectorAll("input.row_" + obj.getAttribute("id").substr(3)), function(elem) {
elem.checked = boolValue;
}
);
}
<table></table>
下面的脚本采用您的脚本并调整问题。 每行的主复选框都有一个 id。而其他人则获得一个类名,该类名的数字与主复选框的 ID 相对应。
当您单击主复选框时,该函数就会执行。
然后它使用 document.querySelectorAll()
使用 id 中的整数选择适当的复选框。 querySelector 返回一个节点列表(一种数组,但不精确)。我们使用 Array 对象的 map 函数迭代所有具有 row_#
类名的复选框。
我们根据该行中的主复选框对复选框(使用 elem
引用)应用 true 或 false。
关于javascript - 复选框显示在for循环中,如何在Javascript中获取getElementById,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31791195/