我有三个图像的数组。我想从onClick
调用该函数。这是我的代码。我知道可以用jQuery完成,但我只是使用纯JavaScript。
的JavaScript
var myArray = ["_images/taste_logo_130w.gif","_images/logo.gif", "_images/winery_sign.jpg"];
var current = 0;
function imageTimer() {
if(current >= array.length) {
documnent.getElementById("logo").src = array[current];
current ++;
}
}
HTML
<img src="_images/logo.gif" id="logo" width="192" height="237" onClick=setInterval("imageTimer()", 3000); />
答案 0 :(得分:1)
也许是这样?
function imageTimer() {
if(current < array.length) {
current++;
}else{
current = 0;
}
documnent.getElementById("logo").src = array[current];
}
或更短:
function imageTimer() {
(current < array.length) ? current++ : current = 0;
documnent.getElementById("logo").src = array[current];
}
答案 1 :(得分:1)
(1)
if(current >= array.length) { // fail always
,因为 current is 0
和 array.length is 3
所以上述情况总会失败。
(2)第4次点击会发生什么,没有图像。因此,最好通过将当前值重置为零来回收它。
代码:
var myArray = ["_images/taste_logo_130w.gif","_images/logo.gif", "_images/winery_sign.jpg"];
var current = 0;
function imageTimer() {
if(current <= array.length) {
documnent.getElementById("logo").src = array[current];
current ++;
}
else {
current = 0; //reset back to zero on 4th click
}
}
答案 2 :(得分:0)
您有一个数组myArray
,但在函数中,您正在调用.lenght
上的array
,因此将其更改为myArray.lenght
,您应该array[current]
是myArray[current]
。如果您if(current >= myArray.lenght)
因为(0> = 3)始终为假,则您的if条件也将始终为false。
试试这个:
var myArray = ["_images/taste_logo_130w.gif","_images/logo.gif", "_images/winery_sign.jpg"];
var current = 0;
function imageTimer() {
if(current < myArray.length) {
documnent.getElementById("logo").src = myArray[current];
current ++;
}
}
答案 3 :(得分:-1)
的javascript:
var myArray = ["_images/
taste_logo_130w.gif","_images/logo.gif",
"_images/winery_sign.jpg"];
var current;
var timr;
function imageTimer() {
if(current < array.length) {
documnent.getElementById
("logo").src = array[current];
current ++;
}
else clearInterval(timr);
}
HTML:
<img src="_images/logo.gif" id="logo"
width="192" height="237" onClick="timr=setInterval
(function(){
current=0;
imageTimer();
}, 3000); "/>