jQuery 如何将元素分配给变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23911492/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I assign an element to variable?
提问by Selenir
For example: I want to create shortcut to element array
例如:我想创建元素数组的快捷方式
var $artifacts = $('.game-artifact');
but atm there aren't any elements with such class. Then comes some code, which adds elements. The question is if, after I add these elements will variable $artifacts still refer to them or it will remain null? If so, how I manage to assign a reference to function to a variable?
但是 atm 没有任何具有此类类的元素。然后是一些添加元素的代码。问题是,在我添加这些元素之后,变量 $artifacts 是否仍然引用它们,或者它会保持为空?如果是这样,我如何设法将函数的引用分配给变量?
回答by mareckmareck
回答by hsz
You can wrap it with function which will return current elements:
您可以使用将返回当前元素的函数包装它:
var artifacts = function(){
return $('.game-artifact');
};
var $artifacts = artifacts();
回答by beliha
You should use .get() over accessing the array directly, to avoid out of bound errors.
您应该使用 .get() 直接访问数组,以避免越界错误。
var lists = $("body li");
console.log(lists.length); // returns 20
console.log(lists.get(25)); // returns undefined.
console.log(lists[25]); // Generates an error.