jquery index()返回-1
为什么我的imageIndex不断返回-1jquery index()返回-1,jquery,Jquery,为什么我的imageIndex不断返回-1 $(function(){ //rotateImages(); setInterval("rotateImages()", 4000); }); var imageIndex = 0; var currentPhoto = $("#photoShow div.current"); function rotateImages(){ var max = $(
$(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>
试试:
尝试:
此语句
var currentPhoto=$(“#photoShow div.current”)代码>的长度为1,因为您的代码只有一个
imageIndex=currentPhoto.index()在这种情况下,代码>应返回0。在控制台日志中,0-1=-1
是输出
编辑:
抱歉,您正在执行var max=$(“#photoShow div”).length代码>和最大值-1。imageIndex应该为零:-(此语句var currentPhoto=$(“#photoShow div.current”);
的长度为1,因为您的代码只有一个
imageIndex=currentPhoto.index();
在这种情况下应该返回0。在控制台日志中,0-1=-1
是输出
编辑:
很抱歉,您正在执行var max=$(“#photoShow div”).length;
和max-1。imageIndex应为零:-($。如果找不到元素,index()将返回-1
根据上面的源代码,在声明currentPhoto之前,您似乎没有等到DOM准备就绪……因此,在定义变量时,元素可能还不存在于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));
}
});
$.index()如果找不到元素,则返回-1
根据上面的源代码,在声明currentPhoto之前,您似乎没有等到DOM准备就绪……因此,在定义变量时,元素可能还不存在于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));
}
});
,这是正确的,。这是正确的。当我将其全部移动到初始jquery函数中时,setInterval无法再找到函数rotateImages()。我得到一个错误::referenceError:找不到变量:rotateImages当我将其全部移动到初始jquery函数中时,setInterval无法再找到函数rotateImages().I获取错误::ReferenceError:找不到变量:rotateImages