【发布时间】:2012-04-03 02:47:58
【问题描述】:
我有一个列出位置的表格,然后允许用户为该位置选择一个或多个权限。我有以下代码工作,我可以选择顶行复选框,您可以选中该列中的所有框。我正在寻找优化我正在做的事情的技巧。您单击“.all###”复选框,所有具有“.XXX”类的复选框都会被选中。如何优化我的 jquery?我仍在学习,虽然我得到了它的工作,但我确定它不是最好的路线。任何帮助,将不胜感激。
这是我的 HTML 代码的一部分
<table>
<colgroup></colgroup>
<colgroup></colgroup>
<colgroup></colgroup>
<colgroup span="5"></colgroup>
<thead>
<tr>
<th class="locationCode">Location Code</th>
<th class="locationName">Name</th>
<th class="locationAddress">Address</th>
<th class="selectOption">Admin</th>
<th class="selectOption">Remote</th>
<th class="selectOption">Support</th>
<th class="selectOption">Misc</th>
<th class="selectOption">Logging</th>
</tr>
</thead>
<tfoot>
<tr>
<td></td>
</tr>
</tfoot>
<tbody>
<tr>
<th colspan="3" class="grayBackground"></th>
<td class="center"><input type="checkbox" class="allAdmin admin"></td>
<td class="center"><input type="checkbox" class="allRemote remote"></td>
<td class="center"><input type="checkbox" class="allSupport support"></td>
<td class="center"><input type="checkbox" class="allMisc misc"></td>
<td class="center"><input type="checkbox" class="allLogging logging"></td>
</tr>
<tr>
<td>VST</td>
<td>Demo #1</td>
<td>1 Street, City State</td>
<td class="center"><input type="checkbox" class="admin"></td>
<td class="center"><input type="checkbox" class="remote"></td>
<td class="center"><input type="checkbox" class="support"></td>
<td class="center"><input type="checkbox" class="misc"></td>
<td class="center"><input type="checkbox" class="logging"></td>
</tr>
还有我的 jQuery
$(function() {
$(".allAdmin").change(function() {
if ($(this).prop("checked")) {
$(".admin").prop("checked", true);
return;
}
$(".admin").prop("checked", false);
});
$(".allRemote").change(function() {
if ($(this).prop("checked")) {
$(".remote").prop("checked", true);
return;
}
$(".remote").prop("checked", false);
});
$(".allSupport").change(function() {
if ($(this).prop("checked")) {
$(".support").prop("checked", true);
return;
}
$(".support").prop("checked", false);
});
$(".allMisc").change(function() {
if ($(this).prop("checked")) {
$(".misc").prop("checked", true);
return;
}
$(".misc").prop("checked", false);
});
$(".allLogging").change(function() {
if ($(this).prop("checked")) {
$(".logging").prop("checked", true);
return;
}
$(".logging").prop("checked", false);
});
});
【问题讨论】:
-
为什么每个“master”复选框都有 2 个类?
class="allAdmin admin"更容易理解为class="allAdmin"。我认为它不会在功能上改变你的 JavaScript。
标签: jquery optimization