필자는 jQuery index() 함수가 기대했던대로 작동하지 않는 이유를 이해하고있다. 아마도 나는 이것을 이해하지 못한다. 보여 드리죠.왜 jQuery .index() 함수가 예상대로 작동하지 않습니까?
새 배열을 설정했습니다. 우리는 나중에 이것을 사용합니다 :
var mySources = new Array();
내 5 개 페이지의 이미지를 가지고 내가 jQuery를 객체에 모두 넣어
<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" />
,이 같은 :
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"]
....
console.log(myVar);
... 수익률이 ...
../images/homeImages/02.jpg
...
var myVar = $(myImages).eq(2).attr('src');
지금 그 변수를 추적하지만 내가 할 때
지금은 이렇게 이 ...
console.log('Index of ' + myVar + " is: " + ($(myVar).index(mySources)));
,451,515,
... 그것은이 반환이 나를 던지고
Index of ../images/homeImages/02.jpg is: -1
. 왜 그것은 retunring 2 일 때 "발견되지 않음"에 대해 -1을 반환 할 것인가? mySources 배열의 두 번째 슬롯을 매트 화합니까?
'myImages'는 이미 jQuery 객체입니다. 당신은'$ (myImages)'를 할 필요가 없다. –