我想制作一个简单的照片库功能。但是,JQuery的click()有一些奇怪的行为。
用户单击前进按钮后,应显示10个下一个图像。用户单击后退按钮后,应显示10个先前的图像。
在下面的代码中,注释了4行在我的代码中正常工作。我希望JQuery click()应该与注释行做同样的事情,但事实并非如此。单击向后和向前几次后,使用JQuery click()的代码不起作用。我想问一下代码的问题在哪里。谢谢。
<script type="text/javascript">
$(document).ready(function() {
var numImages = imagesObj.images.image.length;
var imagePath = "images/";
var currentIndex = 0;
function changeImageList(startIndex){
var imageIndex = 0;
$("#imagesList img").css("display","none");
for (var i=startIndex; i<numImages && i<startIndex + 10; i++)
{
var imageId = "image" + imageIndex;
var image = imagesObj.images.image[i];
$("#" + imageId).attr("src",imagePath + image.imageurl).css("display","");
imageIndex++;
}
currentIndex = startIndex;
if (numImages > currentIndex+10){
$('#forward').css("cursor","pointer");
//document.getElementById("forward").onclick = function(){changeImageList(currentIndex+10);};
$('#forward').click(function(){ changeImageList(currentIndex+10);});
}else{
$('#forward').css("cursor","default");
//document.getElementById("forward").onclick = function(){};
$('#forward').click(function(){});
}
if (currentIndex < 10){
$('#backward').css("cursor","default");
//document.getElementById("backward").onclick = function(){};
$('#backward').click(function(){});
}else{
$('#backward').css("cursor","pointer");
//document.getElementById("backward").onclick = function(){changeImageList(currentIndex-10);};
$('#backward').click(function(){changeImageList(currentIndex-10);});
}
}
changeImageList(0);
});
</script>
</head>
<body>
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td align="center"><img id="backward" src="images/lft_arrow.gif" alt="" width="39" height="44" /></td>
<td id="imagesList" align="center">
<img id="image0" width="77" style="display:none; cursor:pointer" />
<img id="image1" width="77" style="display:none; cursor:pointer" />
<img id="image2" width="77" style="display:none; cursor:pointer" />
<img id="image3" width="77" style="display:none; cursor:pointer" />
<img id="image4" width="77" style="display:none; cursor:pointer" />
<img id="image5" width="77" style="display:none; cursor:pointer" />
<img id="image6" width="77" style="display:none; cursor:pointer" />
<img id="image7" width="77" style="display:none; cursor:pointer" />
<img id="image8" width="77" style="display:none; cursor:pointer" />
<img id="image9" width="77" style="display:none; cursor:pointer" />
</td>
<td align="center"><img id="forward" src="images/rgt_arrow.gif" alt="" width="39" height="44" /></td>
</tr>
</table>
</body>
答案 0 :(得分:2)
这是事件绑定的正常行为:当您致电click
时,事件回调已添加到元素,不会替换现有回调。当您多次单击向后和向前按钮时,您为click
事件分配了多个处理程序,现在您知道这很糟糕:)
您有两种解决方案:
$('#backward').unbind('click')
,这是您代码的简单修复。$('#backward').click(function(){ changeImageList(-10);});
。我发现它更清晰,只需在changeImageList
开头进行简单检查即可计算startIndex
,但您仍需将光标设置为默认/指针。