jquery中的$().each,$.each的區別

來源:互聯網
上載者:User

標籤:

在jquery中,遍曆對象和數組,經常會用到$().each和$.each(),兩個方法。兩個方法是有區別的,從而這兩個方法在針對不同的操作上,顯示了各自的特點。

$().each,對於這個方法,在dom處理上面用的較多。如果頁面有多個input標籤類型為checkbox,對於這時用$().each來處理多個checkbook,例如:

$(“input[name=’ch’]”).each(function(i){
if($(this).attr(‘checked’)==true)
{
//一些作業碼

}

回呼函數是可以傳遞參數,i就為遍曆的索引。

對於遍曆一個數組,用$.each()來處理,簡直爽到了極點。例如:

$.each([{“name”:”limeng”,”email”:”xfjylimeng”},{“name”:”hehe”,”email”:”xfjylimeng”},function(i,n)
{
alert(“索引:”+i,”對應值為:”+n.name);
});

參數i為遍曆索引值,n為當前的遍曆對象.

 

var arr1 = [ “one”, “two”, “three”, “four”, “five” ];
$.each(arr1, function(){
alert(this);
});
輸出:one   two  three  four   five
var arr2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
$.each(arr2, function(i, item){
alert(item[0]);
});
輸出:1   4   7
var obj = { one:1, two:2, three:3, four:4, five:5 };
$.each(obj, function(key, val) {
alert(obj[key]);
});
輸出:1   2  3  4  5

 

在jQuery裡有一個each方法,用起來非常的爽,不用再像原來那樣寫for迴圈,jQuery源碼裡自己也有很多用到each方法。

其實jQuery裡的each方法是通過js裡的call方法來實現的。

下面簡單介紹一下call方法。
call這個方法很奇妙,其實官方的說明是:“調用一個對象的一個方法,以另一個對象替換當前對象。”網上更多的解釋是變換上下文環境,也有說是改變上下文this指標。
call([thisObj[,arg1[, arg2[,   [,.argN]]]]])

參數
thisObj
可選項。將被用作當前對象的對象。
arg1, arg2,  , argN
可選項。將被傳遞方法參數序列。

說明
call 方法可以用來代替另一個對象調用一個方法。call 方法可將一個函數的物件內容從初始的上下文改變為由 thisObj 指定的新對象。

引用網上有一個很經典的例子

Js代碼
function add(a,b)
{
alert(a+b);
}
function sub(a,b)
{
alert(a-b);
}
add.call(sub,3,1);

用 add 來替換 sub,add.call(sub,3,1) == add(3,1) ,所以運行結果為:alert(4);
注意:js 中的函數其實是對象,函數名是對 Function 對象的引用。

具體call更深入的就不在這裡提了。

下面提一下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就有更厲害了,能迴圈每一個屬性
//輸出結果為:1   2  3  4

 

參考文獻:

http://www.frontopen.com/1394.html

jquery中的$().each,$.each的區別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.