2017-01-04 84 views
0

我有腳本咆哮,我需要創建一個函數,更改我的圖像,然後用它與setInterval每2秒更改一次圖像。如何創建一個函數並在函數上調用它

計數器(控制)工作,但它不會更改圖像。

我到底做錯了什麼?

var contar = 0; //counter value 
var pausa = false; 

function passar(){ //function that changes the image 
    $("#"+contar).click(function(){ 
     $(".img").attr('src', 'imagens/'+contar+'.jpg'); //the image is from 1.jpg to 4.jpg 
     $("#"+contar).addClass('active'); 
     console.log(contar); 
    }); 
} 

setInterval(function(){ //setinterval to use the function "passar" to change image 
    contar++; 
     if(contar<=4) { //my limit of images on the html 
      passar(contar); 
      console.log(contar); 
     }else{ 
      contar = 0; 
     }; 
}, 2000); 
+2

請包括您的HTML。我們不知道'.img'可能(或可能不會引用)。此外,[JavaScript控制檯]中的任何錯誤(http://webmasters.stackexchange.com/questions/8525/how-to-open-the-javascript-console-in-different-browsers)? –

+0

passar()應該帶一個參數contar - '函數passar(contar){'編輯:nm,只是看到你有全局變量 – dave

+0

@dave或者不要傳入;因爲它是被忽略的,並且在任何地方都會使用外部的'contar'。不是OP說計數器正在工作,這是圖像變化沒有發生。 –

回答

0

這樣做。刪除點擊事件,看起來沒有必要。

var contar = 0; //counter value 
var max_images = 4; // my limit of images on the html 
var pausa = false; 

function passar(){ //function that changes the image  
    $(".img").attr('src', 'imagens/' + contar + '.jpg'); // the image is from 1.jpg to 4.jpg 
    $("#"+contar).addClass('active'); 
    console.log(contar); 
} 


setInterval(function(){ // setinterval to use the function "passar" to change image 
contar++; 
    if(contar<=max_images) { 
     passar(contar); 
     console.log(contar); 
    }else{ 
     contar = 0; 
    }; 
}, 2000); 

這是假設您的圖像元素具有.img類定義。

+0

是的,我有一個.img類。 這些變化工作得很好,它的工作很好,沒有點擊事件。 –

相關問題