用jQuery方法实现隔行变色和代码注释都在下面↓↓↓
1.html代码
<form>
<div>
<label for="user">姓名</label>
<input type="text" id="user">
</div>
<div>
<label for="age">年龄</label>
<input type="text" id="age">
</div>
<input type="button" value="添加" id="add">
<div>
<input type="button" value="开启偶数行变色" id="oddBtn">
<input type="button" value="开启基数行变色" id="evenBtn">
<input type="button" value="关闭变色" id="closeBtn">
</div>
<input type="number" placeholder="输入变色行数 回车确定" id="num">
</form>
<table border="1" style="width: 50vw;">
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
2.JavaScript代码
var arr = [
{ "user": "wang", "age": 18 },
{ "user": "qian", "age": 80 }
]
function show(arr) {
var str = "";
$.each(arr, function (i, v) {
str += `
<tr>
<td>${arr[i].user}</td>
<td>${arr[i].age}</td>
</tr>
`
})
$("#tbody").html(str)
if (flag1 == "开") {
$("#tbody tr:odd").css({
"background": "red"
})
flag1 = "开"
} else if (flag2 == "开") {
$("#tbody tr:even").css({
"background": "red"
})
flag2 = "开"
} else {
$("#tbody tr:odd").css({
"background": "white"
})
flag1 = "关"
flag2 = "关"
}
}
$(function () {
show(arr)
})
$("#add").click(function () {
let user = $("#user").val()
let age = $("#age").val();
arr.push({ user, age })
show(arr);
})
var flag1 = "关"
var flag2 = "关"
$("#oddBtn").click(function () {
$("#tbody tr:odd").css({
"background": "red"
})
$("#tbody tr:even").css({
"background": "white"
})
})
$("#evenBtn").click(function () {
$("#tbody tr:even").css({
"background": "red"
})
$("#tbody tr:odd").css({
"background": "white"
})
})
$("#closeBtn").click(function () {
$("#tbody tr:odd").css({
"background": "white"
})
$("#tbody tr:even").css({
"background": "white"
})
})
$("#num").keydown(function (event) {
if (event.keyCode == 13) {
var num = $("#num").val();
if (num == "" || num == 0) {
$("#tbody tr").css({
"background": "white"
})
} else if (num > $("#tbody tr").length) {
alert("请输入正确行数")
} else {
$("#tbody tr").eq(--num).css({
"background": "red"
}).siblings().css({
"background": "white"
})
}
}
})
本文地址:https://blog.csdn.net/w1666793979/article/details/112592493