2014-08-31 71 views
1

任何人都有一個線索,爲什麼這個代碼不通過1.fw.png改變我的圖像5.fw.png?圖片Slider-的Javascript

HTML

<div id="slideshow"> 
<img id="slider" src="1.fw.png"> 
</div> 

的JavaScript

function timer(x){ 
var timer = setTimeout(function() {switchPic(x);}, 4000); 
} 

function switchPic(x){ 
x += 1; 
document.getElementById('slider').src = x + ".fw.png"; 
} 

$(document).ready()(function(){ 
document.getElementById('slider').src = x; 
timer(x); 
}); 

一個形象換一個過渡將是一個好處,但只是改變了圖像的本質要求。

回答

1

x是一個局部變量(參數),所以增量變化不會超過switchPic函數。如果有一個全球性的x則陰影;否則timer(x)會導致一個的ReferenceError - 確保你描述什麼「不工作」和這樣怎麼是已知的。

我可能會寫它像這樣:

jQuery(function ($) { 
    var t = -1;    // initial value peicked so x is 1 at first interval 
    function switchIt() { 
     t++;     // change variable caught in closure 
     var x = (t % 5) + 1; // loops through values in 1..5 
     $('#slider').attr("src", x + ".fw.png"); 
    } 
    // set initial image right away 
    switchIt(); 
    // switch image every 4 seconds, forever 
    setInterval(switchIt, 4000); 
}); 
1

謝謝user2864740,我重新寫使用您的信息的代碼,並以正確的數量現在循環也。

$(document).ready(function(){ 
    setInterval(function(){ 

     z = document.getElementById('slider').src; 
     y = z.indexOf(".fw.png"); 
     y = z.slice(y - 1, -7); 
     x = parseInt(y); 
     y = (x % 5) + 1; 
     document.getElementById('slider').src = "/Images/Index/Slider/" + y + ".fw.png"; 

    },4000); 
});