2015-02-11 193 views
0

我有几个黑色的div。jQuery循环事件

<div id='div1'></div> 
<div id='div2'></div> 
<div id='div3'></div> 
<div id='div4'></div> 
<div id='div5'></div> 

我想1日一到负载突出

$('#div1').css('background', 'white'); 

当我点击它,我想我的脚本来突出另一个

$('#div1').click(function() { 
    $('#div4').css('background', 'white'); 
    $('#div1').css('background', 'black'); 
}); 

我想做的事情它按照我想要的顺序。就像一首歌曲的钢琴模式一样.... 1,4,4,3,2,5,直到序列重新设置,并且第一个div再次高亮,这样我可以点击它多少次想。有没有办法使用jQuery来做到这一点?我不能在这个问题上找到任何

回答

1

而不是使用IDS,你可以使用类和一些JavaScript简化它:

HTML

<div></div> 
<div></div> 
<div></div> 
<div></div> 
<div></div> 

CSS

div { 
    background-color: black; 
} 
div.current { 
    background-color: white; 
} 

JavaScript

var sequence = [0, 2, 4, 3, 1], // configure your sequence here - NOTE: starts at 0 
    current = 0; // the current active item in the sequence, initially 0 

// highlight the first div in the sequence 
$('div:eq('+ sequence[current] +')').addClass('current'); 

// on clicking the 'current' one, move highlight to the next div in sequence 
$(document).on('click', '.current', function() { 
    $('div.current').removeClass('current'); // remove current highlight 
    if(++current >= sequence.length) current = 0; // get index of next div in sequence \ 
    $('div:eq('+ sequence[current] +')').addClass('current'); // highlight new div 
}); 

演示:http://jsfiddle.net/b6w9xbxn/1/

+1

很好的解决方案+1。我正在做类似的事情,但你打败了我:http://jsfiddle.net/yn0erc8g/ – 2015-02-11 11:51:03

+0

哇......谢谢,伙计...... – 2015-02-11 11:52:12