【问题标题】:jQuery SetTimeout for Show / Hide div does not work显示/隐藏 div 的 jQuery SetTimeout 不起作用
【发布时间】:2021-08-03 07:09:26
【问题描述】:

我正在编写一个 jQuery,它应该在单击图像后显示/隐藏一系列图像。它基本上是隐藏当前图像并在onClick 事件时显示下一个图像。

到目前为止,我编写的功能除了一个功能外都有效:在图 3 上,我想设置一个计时器,然后切换到图 4,即使用户没有点击它。

我正在使用setTimeout 并触发超时,但它不会切换到下一张图像。

这是我的功能:

(function($) { 
    $(document).ready(function () {
        var count = 0;
        $('.squirrel').click(function () {          
            $(this).hide();
            var next = $(this).next();
            if (next.length == 0){
                next = $(this).parent().find('.squirrel').first();
                count = -1;
            }            
            next.show();            
            if (count == 1) {
                setTimeout(
                    function() {
                        alert("Should switch to 4 now but it doesn't work");                            
                        $(this).hide();
                        var next = $(this).next();          
                        next.show();
              
                        count++;
                    }, 2000
                );
            } else {            
                count++;            
            }       
        });
    });
})(jQuery);

这是 HTML:

<div id="squirrelContainer">
    <img src="1.png" class="squirrel default">
    <img src="2.png" class="squirrel">
    <img src="3.png" class="squirrel" id = "3">
    <img src="4.png" class="squirrel">
</div>

这是JSFiddle

【问题讨论】:

    标签: javascript jquery settimeout show-hide


    【解决方案1】:

    因为您使用的是同一张图片而不是下一张。

    (function($) { 
    $(document).ready(function () {
        var count = 0;
    $('.squirrel').click(function ()
    {
        $(this).hide();
        var next = $(this).next();
        if (next.length == 0)
        {
            next = $(this).parent().find('.squirrel').first();
            count = -1;
        }            
        next.show();
            
        if (count == 1) 
        {
            let that = $(this).next();
            setTimeout(
            function() 
            {
                 console.log("Should switch to 4 now but it doesn't work");
                            
                that.hide();
                var next = that.next();          
                next.show();
                count++;
            }, 2000
            );
        } 
        else 
        {
            count++;
        }
    });
    });
    })(jQuery);
    

    https://jsfiddle.net/dyt9opLz/

    【讨论】:

    • 谢谢你,伙计!我知道我错过了类似的东西。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-18
    • 1970-01-01
    • 2016-01-24
    • 1970-01-01
    • 2012-12-29
    • 2012-09-28
    相关资源
    最近更新 更多