以下代码用于在单击复选框时突出显示表记录。当第一个复选框单击表记录时,表记录以红色突出显示,当第二个复选框被单击时,表记录应以黄色突出显示,当第三个复选框被单击时,表记录应以绿色突出显示。虽然我在样式 none 中使用了 3 种颜色当我点击它们时,其中的一些会突出显示记录
<style>
.cb3 {background-color:yellow;}
.cb2 {background-color:green;}
.cb1 {background-color:red;}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
Array.prototype.remove = function() {
var what, a = arguments, L = a.length, ax;
while (L && this.length) {
what = a[--L];
while ((ax = this.indexOf(what)) !== -1) {
this.splice(ax, 1);
}
}
return this;
};
var checked = [];
$(document).ready(function() {
if (localStorage.getItem("checked") == null)
localStorage.setItem("checked", checked);
$("#Table input").click(function() {
if ($(this).is(":checked")) {
$(this).parent().parent().addClass("highlight");
checked.push($(this).attr("id"));
} else {
$(this).parent().parent().removeClass("highlight");
checked.remove($(this).attr("id"));
}
localStorage.setItem("checked", JSON.stringify(checked));
});
var saved = JSON.parse(localStorage.getItem("checked"));
for (var i = 0;i < saved.length; i++) {
var itemAtIndex = $("#" + saved[i] + "");
itemAtIndex.click();
itemAtIndex.parent().parent().addClass("highlight");
}
});
</script>
<body>
<div class="col-lg-10">
<table id="Table" border="1"><tr>
<td><input type="checkbox" name="cb1" id="cb1" value="y" /></td>
<td>Click me</td>
</tr><tr>
<td><input type="checkbox" name="cb2" id="cb2" value="y" /></td>
<td>Click me</td>
</tr><tr>
<td><input type="checkbox" name="cb3" id="cb3" value="y" /></td>
<td>Click me</td>
</tr></
<table>
</div>
最佳答案
您的 JS 是正确的。在您的 HTML 中,您只需移动每个 id
到 <tr>
行并为每个表记录添加一个类。
<tr id="cb1">
<td><input type="checkbox" name="cb1" value="y" /></td>
<td class=label>Click me</td>
</tr>
然后使用这个 CSS:
#cb3.highlight .label {background-color:yellow;}
#cb2.highlight .label {background-color:green;}
#cb1.highlight .label {background-color:red;}
演示:JSFiddle
关于html - 单击复选框时使用 3 种不同的颜色突出显示表记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45350799/