简体   繁体   English

jQuery设置间隔在WordPress中不起作用

[英]Jquery set interval not working in wordpress

The anchors in the span tag should change every 5 seconds but nothing happens. span标签中的锚点应该每5秒更改一次,但是什么也没有发生。 I've tested that jQuery works in WordPress with alert("test"); 我已经测试过jQuery在alert("test");可以在WordPress中使用alert("test"); at the top of my js file. 在我的js文件的顶部。

    <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);


});

This code doesn't work, i put alert("test"); 该代码不起作用,我将alert("test"); in the function swapImages() but nothing happens. 在函数swapImages()中,但没有任何反应。 I think setInterval is not working. 我认为setInterval无法正常工作。 How do i solve this? 我该如何解决?

Just pass the function directly: 只需直接传递函数:

setInterval(swapImages, 5000);

Passing a string is not a recommended way. 不推荐使用字符串。


Your code doesn't work because swapImages is not a global function. 您的代码不起作用,因为swapImages不是全局函数。 Passing a string to setInterval -- e..g. 将字符串传递给setInterval例如 "swapImages()" -- requires that the function is globally defined ( window.swapImages = function () { ... } ). "swapImages()" - 要求该函数是全局定义的window.swapImages = function () { ... } )。

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

That's why you have to pass the real function or an anonymous function that will call your function . 这就是为什么您必须传递实函数将调用您的函数的匿名函数的原因

For the links from JSFiddle, open the dev tools window (press F12 ) and go to console. 对于来自JSFiddle的链接,请打开“开发工具”窗口(按F12 )并进入控制台。

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

Try this 尝试这个

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM