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