2011-12-03 44 views
0

我知道這對於某人來說會非常簡單,但我只花了2個小時試圖弄清楚它。沒有衝突的全局jQuery變量

如何使用jquery裏面的函數沒有衝突。我不斷收到Uncaught ReferenceError: swapImages is not defined (anonymous function)如果我不使用jQuery不衝突代碼工作正常。 (我不得不使用沒有衝突,因爲它是內置到WordPress)

jQuery(document).ready(function ($) { 
    function swapImages() { 
     var $active = $('#myGallery .active'); 
     var $next = ($('#myGallery .active').next().length > 0) ? $('#myGallery .active').next() : $('#myGallery img:first'); 
     $active.show(function() { 
      $active.show().removeClass('active'); 
      $next.show().addClass('active'); 
     }); 
    } 
    // Run our swapImages() function every 5secs 
    setInterval('swapImages()', 500); 
}) 

See the original question here

+0

你爲什麼不得到您的功能在全球範圍內? –

+0

然後'$ === jQuery'將不可用,除非她使用'window.swapImages = function(){...}'。但是使用全局變量是壞的... – ThiefMaster

回答

4

的問題是,您使用的setInterval不當。 決不傳遞一個字符串,但總是傳遞函數 - 傳遞一個字符串就像使用eval一樣糟糕:

setInterval(swapImages, 500); 

那麼你不需要任何全局變量/函數。

在你需要的任何參數傳遞給函數的情況下,你會包裝在一個匿名函數:

setInterval(function() { /* your code/function call */ }, 500); 
+1

那麼晚上去了,應該問早點! – BandonRandon

0
setInterval(function(){swapImages()}, 500); 
+1

你不需要匿名函數。 'setInterval(swapImages,500)'工作得很好。 – jfriend00