【问题标题】:What are your best practices for looping timed jquery function循环定时 jquery 函数的最佳实践是什么
【发布时间】:2013-11-22 13:55:26
【问题描述】:

当我使用 jQuery 进行循环时,我真的很困惑如何传递值并重新开始。

我的项目是一个“简单”的推荐旋转器。

<div id="testimonials">
    <div class="testimonial">
        <p>You're great!</p>
    </div>
    <div class="testimonial">
        <p>Thanks a lot!</p>
    </div>
    <div class="testimonial">
        <p>Rock on!</p>
    </div>
</div>
<script>
    jQuery(function ($) {
        $( document ).ready(function() {
            function fade() {
                $('.testimonial').hide();
                var t = $('.testimonial').length;
                alert(t);
                for( var i = 1; i <= t; i++){
                    function slideit(){
                       var i = i;
                       $('.testimonial.nth-child(' + i + ')').show('slow');
                       $('.testimonial.nth-child(' + i + ')').hide('slow').delay(2000);
                    }
                    slideit();
                }
            }
            fade();
        });
    });
</script>

现在,我被困住了。克服困难的指针?

【问题讨论】:

  • $('.testimonial.nth-child[' + i + ']') 应该是$('.testimonial:nth-child(' + i + ')')
  • 感谢@Shikiryu。完成!
  • 注意,如果你只是在寻找一个优雅的 jQuery 脚本来解决这个功能,请参阅stackoverflow.com/a/8616480/497438

标签: jquery loops timing


【解决方案1】:

最好的方法是使用setInterval()

var i = 0, // index of element to show
    t = $('.testimonial'), // elements
    max = t.length; // max elements
function fade() {
    t.eq(i).show('slow'); // we show current element
    t.not(':eq('+i+')').hide('slow'); // we hide others
    if(++i >= max) i=0; // we increment index and if we go over max, we reset index
}
window.setInterval(fade,3000); // we call fade every 3 seconds

http://jsfiddle.net/zf5Wb/

【讨论】:

  • 啊。现在,我们正在使用 javascript。我经常依赖 jQuery 为我做我的思考,忘记了直接的 javascript 可能更简单。谢谢!
【解决方案2】:

正如 Shikiryu 建议的那样。

修改代码

$('.testimonial.nth-child[' + i + ']')
$('.testimonial:nth-child(' + i + ')')

【讨论】:

  • 您认为哪个答案有用,请勾选答案或如果您自己找到了解决方案,请发布您的答案。这有助于进入此页面的人们立即找到答案:)
  • 我只是让它呼吸一下。当人们也不检查解决方案时,我很生气。
猜你喜欢
  • 1970-01-01
  • 2019-07-16
  • 1970-01-01
  • 1970-01-01
  • 2023-02-04
  • 2015-07-23
  • 2011-06-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多