要使您的 javascript 代码正常工作,请在 HTML 而不是 ASP 控件中定义您的复选框集合:
<div id="CheckboxList" onclick="CheckBoxToggle()">
<input type="checkbox" value="0" name="checkbox1" /><label for="checkbox1">A</label>
<input type="checkbox" value="1" name="checkbox2" /><label for="checkbox2">B</label>
<input type="checkbox" value="2" name="checkbox3" /><label for="checkbox3">C</label>
<input type="checkbox" value="3" name="checkbox4" /><label for="checkbox4">D</label>
</div>
然后你可以使用这个 javascript 函数:
function CheckBoxToggle() {
var target = event.target || event.srcElement;
if (target.type == 'checkbox') {
var ch = target.parentNode.childNodes;
for (var i = 0; i < ch.length; i++) {
ch[i].checked = false;
}
target.checked = true;
}
}
或者,您可以使用 ASP 控件,但在从 ASP 到 HTML 的转换过程中:
<asp:CheckBoxList ID="chkApplyLimits" runat="server" RepeatColumns="2" ClientIDMode="Static" onclick="CheckBoxToggle()">
<asp:ListItem Text="Yes" Value="1"></asp:ListItem>
<asp:ListItem Text="No" Value="0"></asp:ListItem>
<asp:ListItem Text="No" Value="0"></asp:ListItem>
<asp:ListItem Text="No" Value="0"></asp:ListItem>
</asp:CheckBoxList>
被翻译成这样:
<table id="chkApplyLimits" onclick="CheckBoxToggle()">
<tr>
<td><input id="chkApplyLimits_0" type="checkbox" name="chkApplyLimits$chkApplyLimits_0" value="1" /><label for="chkApplyLimits_0">Yes</label></td><td><input id="chkApplyLimits_2" type="checkbox" name="chkApplyLimits$chkApplyLimits_2" value="0" /><label for="chkApplyLimits_2">No</label></td>
</tr><tr>
<td><input id="chkApplyLimits_1" type="checkbox" name="chkApplyLimits$chkApplyLimits_1" value="0" /><label for="chkApplyLimits_1">No</label></td><td><input id="chkApplyLimits_3" type="checkbox" name="chkApplyLimits$chkApplyLimits_3" value="0" /><label for="chkApplyLimits_3">No</label></td>
</tr><tr>
</table>
所以你的javascript函数需要更改为:
function CheckBoxToggle() {
var target = event.target || event.srcElement;
if (target.type == 'checkbox') {
var table = target.parentNode.parentNode.parentNode.childNodes;
for (var i = 0; i < table.length; i++) {
var tr = table[i].childNodes;
for (var j = 0; j < tr.length; j++) {
if (tr[j].tagName == 'TD')
tr[j].childNodes[0].checked = false;
}
}
target.checked = true;
}
}