首先介绍一下$.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>
效果图