10张照片后计数器未重置为1。为什么?它无穷无尽。 我不明白为什么它不起作用。在计数器达到11后,他必须设置为1。 请帮我。我找不到解决方案。
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script>
$(document).ready(function(){
var timer,
counter = 1,
changepic = function(pic){
var src = pic.attr("src");
counter = counter+1;
if (counter == 11){ ## here is the prblem
counter = 1;
}
pic.attr("src", src.substring(0,src.lastIndexOf('.')-1)+counter+".jpg")
};
$('img').hover(function(){
var $this = $(this);
timer = setInterval(function(){changepic($this);}, 1000);
}, function(){clearInterval(timer);});
});
</script>
</head>
<body>
<table style="float:left;">
<tr><tr><td><img src="testbilder/test.1.jpg"><br>Text</td></tr> </tr>
</table>
</body>
我该如何解决?
答案 0 :(得分:1)
首先,您需要确认问题出在柜台上。添加日志语句并查看Google Chrome开发人员工具中的日志。
if (counter == 11){ ## here is the prblem
counter = 1;
}
console.log('counter : '+counter);
查看你的代码之后......我认为这个问题出现在这个声明中..
pic.attr("src", src.substring(0,src.lastIndexOf('.')-1)+counter+".jpg")
因为对于counter = 10 ... src的值是,
src ='testbilder / test.10.jpg'
现在通过src.substring(0,src.lastIndexOf('。') - 1)+ counter +“。jpg”)对于计数器最多可以工作9但是对于counter = 10 ...这将是
changepic = function(pic){
var src = pic.attr("src"); // here src = 'testbinder/test.10.jpg'
counter = counter+1; // here counter = 11
if (counter == 11){
counter = 1; // here counter = 1
}
// now src.substring(0,src.lastIndexOf('.')-1) = 'testbinder/test.1'
// src.substring(0,src.lastIndexOf('.')-1)+counter+".jpg"='testbinder/test.11.jpg'
pic.attr("src", src.substring(0,src.lastIndexOf('.')-1)+counter+".jpg");
};
}
要解决此问题,请将其更改为..
pic.attr("src", src.substring(0,src.indexOf('.')+1)+counter+".jpg");