2013-02-01 12 views
2

可能重複:
Remove all classes that begin with a certain stringJavascript/jQuery:如何刪除一系列編號的類?

我有一個腳本,它增加了一個六類隨機身體。類別編號介於1和6之間,如下所示:

theme-1theme-6

我需要一個乾淨的方式來刪除它們。現在我有這個:

$('body').removeClass('theme-1'); 
$('body').removeClass('theme-2'); 
$('body').removeClass('theme-3'); 
$('body').removeClass('theme-4'); 
$('body').removeClass('theme-5'); 
$('body').removeClass('theme-6'); 

但它是一種笨重的權利?有沒有一種方法可以說「刪除theme-1theme-6之間的任何類別」?

回答

3

您可以使用循環索引來生成類名稱。

classes = "" 
for(i=1; i < 7; i++) 
    classes += 'theme-' + i + " "; 
$('body').removeClass(classes); 
+1

爲什麼叫'.removeClass'功能的6倍時,它可以接受多個類,並刪除這一切在1個電話嗎? –

+0

謝謝vega很好的建議。 – Adil

+0

謝謝維加,我刪除了這個。 – shrewdbeans

0

你可以在一個循環中清理它們,至少是一點清潔。

1

你可以在一個行這一切結合起來:

$('body').removeClass('theme-1 theme-2 theme-3 theme-4 theme-5 theme-6'); 

或者使用一個循環,但如果類總是 1和6之間的循環,似乎有點小題大做個人。

0

如果你不知道你可能有多少的都有,你應該使用正則表達式:

document.body.className = document.body.className.replace(/(^|)theme-\d+(|$)/g, ' '); 

如果你想留在jQuery的API中,使用此:

$('body').attr('class', function (i, className) { 
    return className.replace(/(^|)theme-\d+(|$)/g, ' '); 
}); 

如果你沒有對body任何其他類,你可以將它們全部刪除一舉:

$('body').removeClass(); 
0

答案posted here。從Pat的代碼如下:

$('body')[0].className.replace(/\theme-.*?\b/g, ''); 

但是從Prestaul這個答案看起來一樣好。使用此功能:

function removeClassByPrefix(el, prefix) { 
    var regx = new RegExp('\\b' + prefix + '.*?\\b', 'g'); 
    el.className = el.className.replace(regx, ''); 
    return el; 
} 
+0

那你爲什麼不把這個問題作爲重複來解決? –

+0

只是將它標記爲僞裝。非常感謝提示! – JakeGould