下面提一下jQuery的each方法的幾種常用的用法
Js代碼
var arr = [ "one", "two", "three", "four"];
$.each(arr, function(){
alert(this);
});
//上面這個each輸出的結果分別為:one,two,three,four
var arr1 = [[1, 4, 3], [4, 6, 6], [7, 20, 9]]
$.each(arr1, function(i, item){
alert(item[0]);
});
//其實arr1為一個二維數組,item相當於取每一個一維數組,
//item[0]相對於取每一個一維數組里的第一個值
//所以上面這個each輸出分別為:1 4 7
var obj = { one:1, two:2, three:3, four:4};
$.each(obj, function(key, val) {
alert(obj[key]);
});
//這個each就有更厲害了,能循環每一個屬性
var arr = [ "one", "two", "three", "four"];
$.each(arr, function(){
alert(this);
});
//上面這個each輸出的結果分別為:one,two,three,four
var arr1 = [[1, 4, 3], [4, 6, 6], [7, 20, 9]]
$.each(arr1, function(i, item){
alert(item[0]);
});
//其實arr1為一個二維數組,item相當於取每一個一維數組,
//item[0]相對於取每一個一維數組里的第一個值
//所以上面這個each輸出分別為:1 4 7
var obj = { one:1, two:2, three:3, four:4};
$.each(obj, function(key, val) {
alert(obj[key]);
});
//這個each就有更厲害了,能循環每一個屬性
//輸出結果為:1 2 3 4
簡單實例:
$(document).ready(function(){
$("button").click(function(){
$("li").each(function(){ //彈出每一個li的文本
alert($(this).text())
});
});
});