簡體   English   中英

jQuery.each()未定義的問題

[英]jQuery.each() undefined issue

我有以下代碼

function myFunction(items) {
   // this prints out 11
   alert(items.length);

   $(items).each(function(i, item) {
       // item is undefined for some reason
   }
}

它提醒物品的長度,它有元素(確切地說是11)。 那么11個項目怎么可能存在,但jQuery仍然通過undefined?

對此的唯一解釋是items數組包含未定義的值,即:

items = [undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined];

其他兩個答案都是完全錯誤的。 each的第一個參數是索引,而不是值,jQuery.fn.each調用jQuery.each。 他們之間沒有消歧。

聽起來你沒有jQuery wrappet set傳遞給你的函數。 如果你傳遞一個array或一個object你需要使用jQuery helper function $ .each()之類的

$.each(items, function(index, element){
});

正如我在其他答案中多次提到的那樣,使用.each()或javascripts native for..in循環遍歷數組是不好的做法。

如果要傳遞arrays使用標准for loop

編輯

事實證明,您實際上可以使用標准數組調用jQuery constructor 但這似乎是一個可怕的業力,你不能調用95%的所有jQuery方法,除非你想崩潰/破壞你的代碼。

由於評論不允許漂亮的代碼列表...(是嗎?):

Animate將對任何事情起作用。 它被記錄為僅針對CSS屬性,但只是為了證明一點:

var foo = { x: 10, y: 12 }; 

$(foo).animate({ x: "+=20", y: "20" }, 1000, 
      function () { alert(foo.x + ":" + foo.y); }); 

將吐出“30:20”。 這有用嗎? 也許不是在日常工作中。 :)

數組的技巧是你將在每個條目中設置相同的屬性。 例:

var foo = [{ x: 10 }, { x: 20 }]; 

$(foo).animate({ x: "+=30" }, 1000, 
      function () { alert(this.x); }); 

吐出“40”和“50”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM