jquery中$.each()方法来循环一个数据列表、jquery循环列表点击事件、循环列表点击事件、初始循环中的第一个为选中状态class,点击改变class


首先介绍一下$.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代表键名,v代表值
                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>

效果图


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM