2011-05-20 103 views
1

爲什麼我的imageIndex保持返回-1;jquery index()返回-1

$(function(){ 
      //rotateImages(); 
     setInterval("rotateImages()", 4000); 
    }); 

    var imageIndex = 0; 
    var currentPhoto = $("#photoShow div.current"); 

    function rotateImages(){ 
     var max = $("#photoShow div").length; 
     imageIndex = currentPhoto.index(); 
     console.log(imageIndex + " :: "+ (max - 1)); 

    } 

HTML:

<body> 

<div id="photoShow"> 
    <div class="current"> 
     <img src="images/Grass.jpg" alt="Photo Gallery" width="400" height="400" class="gallery" /> 
    </div> 
    <div> 
     <img src="images/Leaf.jpg" alt="Photo Gallery" width="400" height="400" class="gallery" /> 
    </div> 
    <div> 
     <img src="images/Spring.jpg" alt="Photo Gallery" width="400" height="400" class="gallery" /> 
    </div> 
    <div> 
     <img src="images/Water.jpg" alt="Photo Gallery" width="400" height="400" class="gallery" /> 
    </div> 
</div> 

+0

[返回'0對我來說](http://jsfiddle.net/Marcel/v7LAb/show),這是正確的。 – Marcel 2011-05-20 04:30:47

回答

1

嘗試:

imageIndex = $('#photoShow').index('.current'); 
0

這是你的代碼語句var currentPhoto = $("#photoShow div.current");長度爲1只有一個<div class="current">

imageIndex = currentPhoto.index();應該在這種情況下返回0。在控制檯日誌0 - 1 = -1是輸出

編輯:
對不起,你正在做var max = $("#photoShow div").length;和max - 1 imageIndex指定的應該是零:-(

3

$的.index()返回-1,如果該元素是不

根據你上面的源代碼,它看起來像你沒有等到DOM在聲明currentPhoto之前準備就緒......所以很有可能當變量存在時,DOM中的元素還不存在

只需將所有內容移動到$ (function(){...})會給你你期待的結果。

$(function(){ 
    //rotateImages(); 
    setInterval("rotateImages()", 4000); 
    var imageIndex = 0; 
    var currentPhoto = $("#photoShow div.current"); 

    function rotateImages(){ 
     var max = $("#photoShow div").length; 
     imageIndex = currentPhoto.index(); 
     console.log(imageIndex + " :: "+ (max - 1)); 
    } 
}); 
+0

當我把它全部移到初始的jquery函數中時,setInterval不能再找到rotateImages()函數。我得到一個錯誤:: ReferanceError:無法找到變量:rotateImages – Chapsterj 2011-05-20 18:56:45