2011-05-20 99 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