我偶然发现了一个有趣的例子,其中创建了一个涉及4个div http://jsfiddle.net/w5YHY/2/的循环
var $elements = $('#One, #Two, #Three, #Four');
$elements.eq(i).fadeIn(1000, function() {
var $self = $(this);
setTimeout(function() {
$self.fadeOut(1000);
anim_loop((i + 1));
}, 3000);
});
循环工作正常。
我心中有以下疑问。
每个单选按钮对应一个div。如果循环位于位置3,则应选择无线电3,依此类推。这是怎么做到的?反之亦然,无线电应该操纵循环,就像双向绑定一样。
此外,单击左右按钮也应该更改循环。因此,假设循环位于第3位并单击左键,则应返回2.
如何在不重复代码的情况下优雅地完成所有这些事件绑定?
答案 0 :(得分:1)
尝试
<button id="left" data-dir="-1">Left</button>
<button id="right" data-dir="1">right</button>
然后
var $elements = $('#One, #Two, #Three, #Four');
var $radios = $('input[name="op"]');
var timer;
function anim_loop(index) {
if(timer){
$elements.filter('.current').stop(true, true).hide().removeClass('current');
clearTimeout(timer)
}
$radios.eq(index).prop('checked', true);
$elements.eq(index).stop(true, true).addClass('current').fadeIn(1000, function() {
var $self = $(this);
timer = setTimeout(function() {
$self.fadeOut(1000).removeClass('current');
anim_loop((index + 1) % $elements.length);
timer = undefined;
}, 3000);
});
}
$radios.click(function(){
anim_loop($radios.index(this));
});
$('#left, #right').click(function () {
var index = $elements.index($elements.filter('.current')) + $(this).data('dir');
anim_loop(index % $elements.length)
})
anim_loop(0); // start with the first element
演示:Fiddle