社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
jQuery.each() 函数用于遍历指定的对象和数组。
$.each( object, callback )
参数 | 描述 |
---|---|
object | Object类型 指定需要遍历的对象或数组。 |
callback | Function类型 指定的用于循环执行的函数。 |
通过这个方法可以将工作中遇到的数据列表如商城里面的商品列表等很好的进行循环,简单方便,下面就是我写的一个案例:
当然这个这个数组对象是我自己模拟的,实际工作中我们只需要根据后台给的接口来进行操作。
html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>商品列表</title>
<meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1,user-scalable=no">
<meta name="apple-mobile-web-app-capable" content="yes"><meta name="format-detection" content="telephone=no" />
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<link rel="stylesheet" type="text/css" href="css/common.css"/>
<link rel="stylesheet" type="text/css" href="css/index.css"/>
</head>
<body>
<div id="active">
<ul class="shop_box">
</ul>
</div>
</body>
</html>
js:
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
var con=[
{
"image1":"img/1524880084962.jpg",
"shopName":"黑花生(100g*15袋/盒)",
"price":190,
"markPrice":200
},
{
"image1":"img/1524879960117.jpg",
"shopName":"黑花生(100g*15袋/盒)",
"price":190,
"markPrice":200
},
{
"image1":"img/1524879605807.jpg",
"shopName":"黑花生(100g*15袋/盒)",
"price":190,
"markPrice":200
},
{
"image1":"img/1524879181488.jpg",
"shopName":"黑花生(100g*15袋/盒)",
"price":190,
"markPrice":200
}
]
var html="";
$.each(con, function(k,v) {//这里的函数参数是键值对的形式,k代表键名,v代表值
html+='<li class="shopBox">'+
'<div class="shopImg"><img src='+con[k].image1+'/></div>'+
'<div class="shopListName">'+con[k].shopName+'</div>'+
'<div class="shopPrice">'+
'<span class="price">¥'+con[k].price+'</span>'+
'<span class="marketPrice">¥'+con[k].markPrice+'</span>'+
'</div>'+
'</li>'
});
$(".shop_box").append(html);
})
</script>
效果图:
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!