我有幾個div具有相同的類。我想隨機給每個div添加一個(不同的)類,但是在彼此之後沒有重複添加的類。隨機添加相同類的div的類
這裏是我的HTML範例:什麼應該被添加
<div class="sometext"> some text here </div>
<div class="sometext"> some other text here </div>
<div class="sometext"> some more text here </div>
<div class="sometext"> some more text here </div>
<div class="sometext"> some more text here </div>
例如CSS:
.addedclass1 {...}
.addedclass2 {...}
.addedclass2 {...}
.addedclass3 {...}
.addedclass4 {...}
什麼我喜歡在看到底:
<div class="sometext addedclass3"> some text here </div>
<div class="sometext addedclass2"> some other text here </div>
<div class="sometext addedclass4"> some more text here </div>
<div class="sometext addedclass1"> some more text here </div>
<div class="sometext addedclass2"> some more text here </div>
我有一些jquery隨機添加的類,但它允許重複:
$(document).ready(function() {
var classes = ['addedclass1', 'addedclass2', 'addedclass3', 'addedclass4'];
$('.sometext').each(function(i) {
$(this).addClass(
classes[Math.floor(Math.random()*classes.length)]);
});
});
我很親切任何幫助 - 我是一個該死的初學者:)
非常感謝 - 像一個迷人的工作! :) – benniy