2012-02-29 73 views
1

我有问题,理解为什么我的jQuery index()函数没有按照我期望的方式执行。也许我不理解这一点。我来给你展示。我设置了一个新数组。稍后,我们将使用这个:为什么jQuery .index()函数的行为不像我期望的那样?

var mySources = new Array(); 

我有我的网页上5张图片:

<div id="homeSlides"> 
     <img src="../images/homeImages/00.jpg" width="749" height="240" alt="myAltTag" /> 
     <img src="../images/homeImages/01.jpg" width="749" height="240" alt="myAltTag" /> 
     <img src="../images/homeImages/02.jpg" width="749" height="240" alt="myAltTag" /> 
     <img src="../images/homeImages/03.jpg" width="749" height="240" alt="myAltTag" /> 
     <img src="../images/homeImages/04.jpg" width="749" height="240" alt="myAltTag" /> 

我把他们都在一个jQuery对象,像这样:

var myImages = $("#homeSlides img"); 

现在,对于每一个,我提取src属性并将它推入mySources数组,如下所示:

$(myImages).each(function(index) { 
     mySources[index] = $(this).attr('src'); 
}); 

现在,我将运行阵列到FireBug控制台以确保它能够正常工作。

这...

console.log(mySources); 

...返回此...

["../images/homeImages/00.jpg", "../images/homeImages/01.jpg", "../images/homeImages/02.jpg", "../images/homeImages/03.jpg", "../images/homeImages/04.jpg"] 

...这是我的期望。

现在我这样做:

var myVar = $(myImages).eq(2).attr('src'); 

正追踪该变量...

console.log(myVar); 

...返回此...

../images/homeImages/02.jpg 

但后来当我做这...

console.log('Index of ' + myVar + " is: " + ($(myVar).index(mySources))); 

...它返回:

Index of ../images/homeImages/02.jpg is: -1 

这是扔我。为什么当它应该重新调整2时它会返回-1作为“未找到”。它确实覆盖了mySources数组中的第二个插槽,不是吗?

+0

'myImages'已经是一个jQuery对象。您不需要执行'$(myImages)' – 2012-02-29 17:43:05

回答

3

您正在尝试使用数组的索引()。它不打算用于jQuery元素对象以外的其他任何东西。

使用$ .inArray()将是更好的方法

+0

是的,就是这样。谢谢你,并感谢其他回应的人。总是感激! – 2012-02-29 18:26:47

2

您可能有向后的功能。你可以尝试:

$(mySources).index(myVar) 
+2

+1或更好的是,'$ .inArray(mySources,myVar)'。 – 2012-02-29 17:29:24

+0

@ T.J.Crowder实际上'$ .inArray(myVar,mySources)'是正确的方法 – 2012-02-29 17:57:10

+0

@JoseRuiSantos:确实如此。 jQuery的参数顺序是我持续受挫的根源。 :-) – 2012-02-29 17:58:44

相关问题