为什么jQuery .index()函数的表现不像我期望的那样?

时间:2012-02-29 17:22:12

标签: javascript jquery

我在理解为什么我的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

这让我失望。当它应该重新调整时,为什么它会为“未找到”返回-1。它确实覆盖了mySources数组中的第二个插槽,没有?

2 个答案:

答案 0 :(得分:3)

您正在尝试在数组上使用index()。它不能用于除jQuery元素对象之外的任何东西。

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

答案 1 :(得分:2)

你可能会向后退一步。你能尝试一下:

$(mySources).index( myVar )