2017-05-22 7 views
1

ボタンをクリックすると、クラスが各divを上下に回転します。今まで私ができるのは、クラスを回転させることだけですが、同じdivのクラスを回転させるだけです。複数のクラスをDOM上の複数の要素に回転


 

 
var classes = ['a', 'b', 'c']; // the different classes to rotate through each div 
 

 

 

 

 
$('div').each(function() {  // the div needs to rotate classes over and over 
 
    var i = 0; 
 
    
 
    $('button').click(function() { 
 
     $('div').removeClass(classes[ i ]); 
 
     i = ++i % classes.length;    
 
     $('div').addClass(classes[ i ]); 
 
    }); 
 
});
div { color:white; margin: 4px; width: 100px; height: 100px; } 
 
.a { 
 
    background-color: blue; 
 
} 
 

 
.b { 
 
    background-color: red; 
 
} 
 

 
.c { 
 
    background-color: green; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script> 
 
<div class="a"></div> //class change on click to b, than c, back to a.. 
 
<div class="b"></div> //this change to c than a than b .. 
 
<div class="c"></div> // basically these classes always rotate 
 

 
<button> 
 
rotate 
 
</button>

答えて

1
  1. まず本体の外に変数を初期化し、それが再び再初期化しないように 文書準備セクションの内側に宣言します。
  2. 配列をシフトし、クラスの追加/削除を行います。

var classes ; 
 
$(document).ready(function() { 
 
classes = ['a', 'b', 'c']; 
 
}); 
 

 
    
 
    $('button').click(function() { 
 
    debugger; 
 
    var i = 0; 
 
    var remove = classes.shift(); 
 
     classes.push(remove) 
 
    $('div').each(function(key) { 
 
    
 
    $(this).removeClass() 
 
    
 
    $(this).addClass(classes[i]); 
 
     i++; 
 
     
 
    }); 
 
});
div { color:white; margin: 4px; width: 100px; height: 100px; } 
 
.a { 
 
    background-color: blue; 
 
} 
 

 
.b { 
 
    background-color: red; 
 
} 
 

 
.c { 
 
    background-color: green; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script> 
 
<div class="a"></div> //class change on click to b, than c, back to a.. 
 
<div class="b"></div> //this change to c than a than b .. 
 
<div class="c"></div> // basically these classes always rotate 
 

 
<button> 
 
rotate 
 
</button>

関連する問題