jquery中$.each()方法来循环一个数据列表、jquery循环列表点击事件

首先介绍一下$.each有两个参数,分别是object和callback

$.each( object, callback )

object:需要遍历的对象或数组。

callback:每个成员/元素执行的回调函数。

直接上代码

css

*{margin: 0;padding: 0;}
.shop_box{width: 100%;}
.shopContent{width:90%;height:80px;margin: auto; display: flex;align-items: center;justify-content: space-between;border-bottom: 1px solid #eee;}
.shopImg{width: 100px;height: 60px;}
.selected{color: red;}

html

<div class="shop_box">

</div>

js

复制代码
<script src="./jquery-3.3.1/jquery-3.3.1.min.js"></script>
<script>
        $(function(){
            var con=[
                {
                    "imges":"./imgs/1.jpg",
                    "productName":"和田玉",
                },
                {
                    "imges":"./imgs/1.jpg",
                    "productName":"和田玉",
                },
                {
                    "imges":"./imgs/1.jpg",
                    "productName":"和田玉",
                },
                {
                    "imges":"./imgs/1.jpg",
                    "productName":"和田玉",
                }
            ]
            var html="";
            $.each(con, function(i,v) {//这里的函数参数是键值对的形式,i代表下标(index),v代表值(value)
                html+='<div class="shopContent">'+
                        '<img class="shopImg" src='+con[i].imges+'>'+
                        '<p class="shopListName">'+con[i].productName+'</p>'+
                    '</div>'
            });
            $(".shop_box").append(html);
            $(".shopContent").eq(0).addClass('selected')  //给第一个shopContent盒子添加selected样式
            $(".shopContent").click(function(){
                console.log($(this).index())         //打印点击列表的索引
                $(this).addClass('selected').siblings().removeClass('selected');   //切换点击后的状态
            })
        })
</script>
复制代码

效果图

posted @   eternityQSL  阅读(646)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通

喜欢请打赏

扫描二维码打赏

支付宝打赏

点击右上角即可分享
微信分享提示