简体   繁体   English

window.setInterval()调用的jQuery .toggle()无法正常工作

[英]jQuery .toggle() called by window.setInterval() not functioning

I am trying to alternate between two logos every 5 seconds using the following code: 我正在尝试使用以下代码每5秒在两个徽标之间切换:

window.setInterval(
    function () {
        //breakpoint 1
        $("#logo").toggle(
            function() {
                //breakpoint 2
                $(this).attr('src', '/Images/logo1.png');
            },
            function() {
                //breakpoint 3
                $(this).attr('src', '/Images/logo2.png');
            }
        );
    },
    5000
);

I can get a simple toggle to work, but when I introduce the toggle within window.setInterval(), the toggle's two handlers won't fire. 我可以使用一个简单的切换器来工作,但是当我在window.setInterval()中引入切换器时,切换器的两个处理程序将不会触发。

I set breakpoints on the lines directly beneath the comments in the code above. 我在上面代码的注释正下方的行上设置了断点。 Breakpoint 1 hits every 5 seconds. 断点1每5秒命中一次。 However, Breakpoint 2 and 3 never hit. 但是,断点2和3从未命中。

Why are neither of the toggle function's handlers firing? 为什么两个切换功能的处理程序都不触发?

toggle() needs to be click ed as far as I know.... 据我所知,需要click toggle()

So, 所以,

   $("#logo").toggle(
        function() {
            //breakpoint 2
            $(this).attr('src', '/Images/logo1.png');
        },
        function() {
            //breakpoint 3
            $(this).attr('src', '/Images/logo2.png');
        }
    );

window.setInterval(
    function () {        
        $("#logo").trigger('click');
    },
    5000
);

Sounds like jQuery doesn't finds the #logo element. 听起来jQuery找不到#logo元素。

How does the HTML markup look like? HTML标记的外观如何?

You can try this to see if jQuery finds the #logo element: 您可以试试看jQuery是否找到#logo元素:

//Firebug way
console.log($('#logo').length)

//alert way
alert($('#logo').length)

..fredrik ..fredrik

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

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