使用数组项作为选择器对象

时间:2013-06-11 22:34:17

标签: jquery arrays

我正在搞乱阵列并且有一个非常基本的问题。 假设我有这个html-markup:

<div id="1" style="width: 50px; height: 50px; background-color: #ff0; display: none;"></div>
<div id="2" style="width: 50px; height: 50px; background-color: #ffc; display: none;"></div>
<div id="3" style="width: 50px; height: 50px; background-color: #fcc; display: none;"></div>

并创建以下数组:

var testArr = ['$("#1")', '$("#2")', '$("#3")'];

为什么我无法执行以下功能:

 function showArr() { testArr[2].show(); 
  };
 showArr();

因此不应该#3显示?

感谢

2 个答案:

答案 0 :(得分:3)

没有。这不起作用,因为您试图在字符串上运行函数。

testArr[2]'$("#3")'。不是jQuery对象:它是包含代码的字符串。因此testArr[2].show()表示'$("#3")'.show()。由于字符串没有show方法,因此无效。

您需要存储jQuery对象,而不是字符串:

var testArr = [$("#1"), $("#2"), $("#3")];

答案 1 :(得分:1)

首先,ID不能以数字开头。其次,不要将它存储为字符串,只存储对象。

testArr = [ $('#item-1'), $('#item-2') ];