<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery索引操作示例</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
.item {
padding: 10px;
margin: 5px;
border: 1px solid #ccc;
background-color: #f9f9f9;
}
.highlight {
background-color: yellow;
font-weight: bold;
}
a {
color: blue;
text-decoration: underline;
}
</style>
</head>
<body>
<h1>jQuery通过索引值操作元素</h1>
<div class="container">
<div class="item">项目1</div>
<div class="item">项目2</div>
<div class="item">项目3</div>
<div class="item">项目4</div>
<div class="item">项目5</div>
</div>
<button id="btnFirst">高亮第一个</button>
<button id="btnLast">高亮最后一个</button>
<button id="btnThird">高亮第三个</button>
<button id="btnReset">重置所有</button>
<script>
$(document).ready(function() {
// 通过索引获取并操作元素
$("#btnFirst").click(function() {
$(".item").removeClass("highlight");
$(".item:eq(0)").addClass("highlight"); // 索引0表示第一个
});
$("#btnLast").click(function() {
$(".item").removeClass("highlight");
$(".item:eq(-1)").addClass("highlight"); // 索引-1表示最后一个
});
$("#btnThird").click(function() {
$(".item").removeClass("highlight");
$(".item:eq(2)").addClass("highlight"); // 索引2表示第三个
});
$("#btnReset").click(function() {
$(".item").removeClass("highlight");
});
// 另一种通过索引操作的方式
$(".item").each(function(index) {
$(this).attr("data-index", index); // 为每个元素设置data-index属性
// 点击时显示索引
$(this).click(function() {
alert("你点击了索引为 " + index + " 的元素");
});
});
});
</script>
</body>
</html>
jQuery索引操作示例
于 2025-05-13 16:25:13 首次发布