$.each()和$().each(),以及forEach()的用法


1.forEach是js中遍歷數組的方法,如下

var arr=[1,2,3,4];
arr.forEach(function(val,index,arr){//val為數組中當前的值,index為當前值的下表,arr為原數組
arr[index]=2*val;
});
console.log(arr);//結果是修改了原數組,為每個數乘以2

2.$.each()是jquery中遍歷數組的方法,如下

var arr=[1,2,3,4];
$.each(arr,function(i,n){
alert("索引"+i+"對應的值"+n);
});

3.$().each()方法規定為每個匹配元素規定運行的函數,如下:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("li").each(function(){
alert($(this).text())
});
});
});
</script>
</head>
<body>
<button>輸出每個列表項的值</button>
<ul>
<li>Coffee</li>
<li>Milk</li>
<li>Soda</li>
</ul>
</body>
</html>
如果有什么不對的地方歡迎指正!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM