简体   繁体   English

jQuery.each()未定义的问题

[英]jQuery.each() undefined issue

I have the following code 我有以下代码

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

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

It I alert the length of items, it has elements in it (11 to be exact). 它提醒物品的长度,它有元素(确切地说是11)。 so how could 11 items be present, but jQuery still pass undefined? 那么11个项目怎么可能存在,但jQuery仍然通过undefined?

The only explanation for this is the that items array contains values which are undefined, ie : 对此的唯一解释是items数组包含未定义的值,即:

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

Both of the other answers are wholly incorrect. 其他两个答案都是完全错误的。 The first parameter of each is the index, not the value, and jQuery.fn.each calls jQuery.each. each的第一个参数是索引,而不是值,jQuery.fn.each调用jQuery.each。 There is no disambiguation between them. 他们之间没有消歧。

It sounds like you are not passing a jQuery wrappet set to your function. 听起来你没有jQuery wrappet set传递给你的函数。 If you pass an array or an object you need to use the jQuery helper function $.each() like 如果你传递一个array或一个object你需要使用jQuery helper function $ .each()之类的

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

As I already mentioned several times in other answers, it is bad practice to loop over an array with .each() or javascripts native for..in . 正如我在其他答案中多次提到的那样,使用.each()或javascripts native for..in循环遍历数组是不好的做法。

If you are passing arrays use a standard for loop . 如果要传递arrays使用标准for loop

edit 编辑

As it turns out, you actually really can call the jQuery constructor with a standard array. 事实证明,您实际上可以使用标准数组调用jQuery constructor But it seems like terrible karma to do so, you can't call 95% of all those jQuery methods, unless you want to crash / corrupt your code. 但这似乎是一个可怕的业力,你不能调用95%的所有jQuery方法,除非你想崩溃/破坏你的代码。

Since comments don't allow pretty code listings ... (do they?): 由于评论不允许漂亮的代码列表...(是吗?):

Animate will work against anything. Animate将对任何事情起作用。 It's documented as only working against CSS properties, but just to prove a point: 它被记录为仅针对CSS属性,但只是为了证明一点:

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

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

Will spit out "30:20". 将吐出“30:20”。 Is this useful? 这有用吗? Perhaps not in everyday work. 也许不是在日常工作中。 :) :)

The trick with arrays is you'll set the same property across each entry. 数组的技巧是你将在每个条目中设置相同的属性。 Example: 例:

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

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

Spits out "40" and "50". 吐出“40”和“50”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM