[英]Why Isn't the jQuery .index() function behaving like I expect here?
I am having issues understanding why my jQuery index() function is not performing the way I expect it to. 我在理解为什么我的jQuery index()函数没有按我期望的方式执行时遇到问题。 Perhaps I'm not understanding this. 也许我不明白这一点。 Let me show you. 让我演示给你看。
I set up a new array. 我建立了一个新的数组。 We'll use this later: 稍后我们将使用它:
var mySources = new Array();
I have 5 images on my page: 我的页面上有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" />
I put them all in an jQuery object, like this: 我将它们全部放在jQuery对象中,如下所示:
var myImages = $("#homeSlides img");
Now, for each one, I extract the src attribute and push it into the mySources array like this: 现在,对于每一个,我都提取src属性并将其推入mySources数组,如下所示:
$(myImages).each( function(index) {
mySources[index] = $(this).attr('src');
});
Now, I will run the array to the FireBug console to make sure it worked. 现在,我将阵列运行到FireBug控制台以确保其正常工作。
This... 这个...
console.log(mySources);
...returns this... ...返回...
["../images/homeImages/00.jpg", "../images/homeImages/01.jpg", "../images/homeImages/02.jpg", "../images/homeImages/03.jpg", "../images/homeImages/04.jpg"]
...which is what I expect. ...这是我的期望。
Now I do this: 现在,我这样做:
var myVar = $(myImages).eq(2).attr('src');
Tracing that variable now... 现在跟踪该变量...
console.log(myVar);
...returns this... ...返回...
../images/homeImages/02.jpg
But then when I do this... 但是当我这样做时...
console.log('Index of ' + myVar + " is: " + ($(myVar).index( mySources )) );
...it returns this: ...它返回此:
Index of ../images/homeImages/02.jpg is: -1
This is throwing me. 这把我丢了。 Why would it return -1 for "not found" when it should be retunring 2. It does mat the second slot in the mySources array, no? 当它应该重新调整2时,为什么会为“未找到”返回-1。它确实与mySources数组中的第二个插槽匹配,不?
You are trying to use index() on an array. 您正在尝试在数组上使用index()。 It is not intended to be used for anything other than jQuery element objects. 除jQuery元素对象外,不得将其用于任何其他用途。
Using $.inArray() would be the better method 使用$ .inArray()将是更好的方法
You may have the function backwards. 您可能具有向后的功能。 Can you try: 你能试一下吗:
$(mySources).index( myVar )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.