2015-11-24 65 views
1

我有一個調用的加入到我的div類的隨機數的函數:如何添加類的列表,並只顯示JavaScript中的最後一個?

htmlFields[i].classList.add(numbers[i]); 

numbers[i]可以添加任意類:'one','two','three','four','five'

而我的div已有'static''static2'類被添加隨機班像這樣:

<div class="static static2 five one"> 
<div class="static static2 two four one"> 
<div class="static static2 one three four"> 
<div class="static static2 five one"> 
<div class="static static2 one five four"> 

我想保留靜態類並只添加隨機類中的最後一個類。我試圖使用setAttribute()方法,但它刪除了靜態類。

那麼我怎樣才能添加最後一個'隨機類',並保持靜態類在同一時間?

+0

請出示所有你試圖添加最後一個隨機類的代碼。 – AtheistP3ace

+0

您可能正在尋找'addClass()'而不是'setAttribute',它改變了所有的類元素 –

+0

@luigonsec - 'addClass'是一個jQuery(jQuery沒有被用在這個問題中)wrapper圍繞'classList.add' (在問題的第一個代碼示例中使用)。 – Quentin

回答

0

要麼顯式刪除所有其他隨機類,要麼使用setAttribute並重新添加靜態類。

0

刪除所有 「隨機」 類:

for (var j = 0; j < numbers.length; ++j) 
    // it's safe to "remove" a class that isn't actually set, 
    // so we don't need to check 
    htmlFields[i].classList.remove(numbers[j]); 

然後添加你想要的。

htmlFields[i].classList.add(numbers[i]); 
0

不知道你到底通過隨機類的意思,並要添加這些類之一,有什麼條件,但這裏是你如何添加類,而不會失去你的靜態類。

var elems = Array.prototype.slice.call(document.querySelectorAll('.static')), 
 
    numbers = ['one','two','three','four','five']; 
 

 
elems.forEach(function(elem, i) { 
 
    elem.className = elem.className + " " + numbers[i]; 
 
});
<div class="static static2"></div> 
 
<div class="static static2"></div> 
 
<div class="static static2"></div> 
 
<div class="static static2"></div> 
 
<div class="static static2"></div>

1

在你的函數調用的setAttribute之前,您需要將當前類存儲在變量,並添加您的隨機數類如下面的代碼:

var currentClass = htmlFields[i].getAttribute('class'); 
currentClass += " " + numbers[i]; 
htmlFields[i].setAttribute('class', currentClass); 
相關問題