jQuery索引操作示例

<!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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值