我有问题,理解为什么我的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数组中的第二个插槽,不是吗?
'myImages'已经是一个jQuery对象。您不需要执行'$(myImages)' – 2012-02-29 17:43:05