![](/img/trans.png)
[英]jQuery.each(values, function(i,v){ … }) Why v is undefined?
[英]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.