2015-02-11 191 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