<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>each遍历方法</title>
<script type="text/javascript" src="../jquery-2.1.1.min.js"></script>
<style type="text/css">
*{margin:0;padding:0;list-style-type:none;}
ul{margin:0 auto;width:600px;text-align:center;}
a{margin:10px auto;width:60px;text-align:center;display:block;background-color:#c20007;color:#fff;}
#tota{text-align:center;}
</style>
</head>
<body>
<ul>
<li>
<input type="text" name="" id="" value="1" />
<span id="">
100
</span>
</li>
<li>
<input type="text" name="" id="" value="2" />
<span id="">
200
</span>
</li>
<li>
<input type="text" name="" id="" value="3" />
<span id="">
300
</span>
</li>
<li>
<input type="text" name="" id="" value="4" />
<span id="">
400
</span>
</li>
</ul>
<div id="tota">
<label>总值:</label>
<span id="totalCount">
</span>
</div>
<a href="javascript:;">计算</a>
</body>
</html>
<script type="text/javascript">
$(function(){
var arr=[1,2,3,4,5];
var obj = {0:1,1:2,2:3,3:4,length:4};//这是一个伪数组(因为里面有0到length-1的对象,还有length,因为数组中的格式就是这样的,所以称为伪数组)
arr.forEach(function(val,index){//原生的forEach,只能遍历数组,不能遍历字符串和对象
console.log(val+'---'+index)
})
$.each(arr, function(i,v) {//这是jq中的遍历方法(索引,数值)
console.log(i,v)
});
$.each(obj,function(e,v){
console.log(e,v)
})
$('a').click(function(){
var li = $('li')
var total = 0;
var totalArr=[]
$('li').each(function(){
//JSON.parse() 将获取出来的字符串数据转为数字数据,以便于后面的相加
var test={num:JSON.parse($(this).find('span').text().trim()), Price:addCount = JSON.parse($(this).find('input').val())}
console.log(test)//打印最终的对象值
totalArr.push(test)//合并在一个数组中
})
console.log(totalArr)
totalArr.forEach(function(item,i){//循环数组(当前值,下标)
total+=item.Price * item.num //最终值 = 单价 * 数量
$('#totalCount').text(total) //赋值
})
});
});
</script>
each与forEach遍历方法
最新推荐文章于 2024-02-07 21:00:00 发布