2014-11-03 40 views
-1

span標籤中的錨點應該每5秒更換一次,但沒有任何反應。 我測試過,jQuery在WordPress的作品alert("test");在我的js文件的頂部。jquery設置的間隔在wordpress中不工作

<div class="img_ad"><span><a class="active"><img src="http://www.test.co.uk/wp-content/uploads/2014/10/client3.png" /></a> 
    <a><img src="http://www.test.co.uk/wp-content/uploads/2014/10/client1.png" /></a> 
    <a><img src="http://www.test.co.uk/wp-content/uploads/2014/10/client2.png" /></a></span><span></span><span></span> 
</div> 

-

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


    function swapImages(){ 
     var $active = $('.img_ad').find("span:first").find(".active"); 
     var $next = ($('.img_ad').find("span:first").find('.active').next().length > 0) ? $('.img_ad').find("span:first").find('.active').next() : $('.img_ad').find("span:first").find('a:first'); 
     $active.fadeOut(function(){ 
     $active.removeClass('active'); 
     $next.fadeIn().addClass('active'); 
     }); 
    } 

    // Run our swapImages() function every 5secs 
     setInterval('swapImages()', 5000); 


}); 

此代碼不能正常工作,我把alert("test");在功能swapImages(),但沒有任何反應。我認爲setInterval不起作用。我如何解決這個問題?

回答

0
setInterval(function(){ 
    swapImages() 
},5000); 

試試這個

2

就直接傳遞給函數:

setInterval(swapImages, 5000); 

傳遞一個字符串不是一個推薦的方式。


您的代碼不起作用,因爲swapImages不是全局函數。將字符串傳遞給setInterval - e ..g。 "swapImages()" - requires that the function is globally definedwindow.swapImages = function() { ... })。

(function() { 
    function foo() { 
     console.log(1); 
    } 
    setInterval("foo()", 100); // foo is not defined 
})(); 

這就是爲什麼you have to pass the real functionan anonymous function that will call your function

對於JSFiddle的鏈接,打開開發工具窗口(按F12)並轉到控制檯。