$(function(){
var els = [];
var m = $("#container");
m.attr({"style" : "width:50%;"});
$(".grid").each(function(e){
els.push(this);
});
var n = els[3];
n.attr({"style" : "width:50%;"}) //error
});
你好,我是 DOM 操作的新手。我想知道为什么上面的 JQuery 为 var m 返回 [Object][Object],而为 var n 返回 [Object][HTMLDivElement]。
由于这种行为,我无法使用诸如 n.attr(args) 之类的语句。
TypeError: n.attr is not a function
最终,我想将每个 .grid 元素存储在一个数组中,并遍历它们,同时设置属性。
更准确地说,我有一个 6x3 的 div 元素网格,每次加载页面时,它们都会被赋予一个随机的 animation-duration 因为它们是动画淡入和淡出 View 的.
为什么我不能使用 n.attr()?
最佳答案
那是因为 .each()
循环中的 this
是实际的 DOM 元素,而不是 jQuery 对象。如果您希望数组中的项目是 jQuery 对象,您需要自己将它们包装在一个对象中:
els.push($(this));
或者,您可以在访问 DOM 元素时将其包装起来:
var n = $(els[3]);
来自 jQuery .each() :
More importantly, the callback is fired in the context of the current DOM element, so the keyword
this
refers to the element.
和
To access a jQuery object instead of the regular DOM element, use
$( this )
关于javascript - 简单示例 : Setting attributes by iterating,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48494638/