单击按钮即可停止循环功能 [英] Stop loop function on a button's click

查看:133
本文介绍了单击按钮即可停止循环功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一系列数组,它们使用jquery循环一个接一个地显示.

I've a series of arrays which I'm displaying one after another using jquery loop.

检查 JSFiddle演示.

现在,当用户单击立即停止"按钮时,我想停止它.

Now I want to stop it when a user click on "stop it now" button.

HTML:

<h1>Lorem ipsumd dolor sit amet.</h1>
<div id="div1">Answer One</div>
<div class="stop">
    <button>Stop it Now.</button>
</div>

CSS:

body{text-align:center;}
h1{padding:30px; margin:0 0 0 30px;}
#div1{padding:20px;margin-top:0; text-align:center;}

jQuery

$(document).ready(function() {

var items = ["Answer Two", "Answer Three", "Answer Four", "Answer Five", "Answer Six", "Answer One"],
    $text = $( '#div1' ),
    delay = .2; //seconds

function loop ( delay ) {
    $.each( items, function ( i, elm ){
        $text.delay( delay*1E3).hide();
        $text.queue(function(){
            $text.html( items[i] );
            $text.dequeue();
        });
        $text.show();
        $text.queue(function(){
            if ( i == items.length -1 ) {
                loop(delay);   
            }
            $text.dequeue();
        });
    });
}

loop( delay );
});

我该如何实现?

推荐答案

一种解决方案是使用 .stop(true, false) .这样做将清除队列,并且不执行挂起的功能.

One solution is to use .stop(true, false). Doing this will clear the queue and without executing the pending functions.

$("button").on("click", function() {
    $text.stop(true, false);
})

更新了小提琴

这篇关于单击按钮即可停止循环功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆