您可以遍歷每個找到的節點並遍歷這些類以查找匹配;如果發現,刪除類和記錄它:
var found = [];
$('div[class*="some-class-"]').each(function() {
var classes = this.className.split(/\s+/),
$this = $(this);
$.each(classes, function(i, name) {
if (name.indexOf('some-class-') === 0) {
$this.removeClass(name);
found.push(name);
}
});
});
注意,像div[class*="some-class-"]
選擇是相當昂貴的,因爲你需要無論如何執行額外的處理,這將是容易,只需遍歷所有div
標籤並對其進行處理:
var elements = document.getElementsByTagName('div'),
found = [];
$.each(elements, function(i, element) {
var classes = element.className.split(/\s+/);
$.each(classes, function(i, name) {
if (name.indexOf('some-class-') === 0) {
$(element).removeClass(name);
found.push(name);
}
});
});
現代瀏覽器暴露Element.classList
,你可以用它來操縱類名和Array.forEach
迭代:
var found = [];
[].forEach.call(document.getElementsByTagName('div'), function(element) {
(function(names, i) {
while (i < names.length) {
var name = names[i];
if (name.indexOf('some-class-') === 0) {
names.remove(name);
found.push(name);
} else {
++i;
}
}
}(element.classList, 0));
});
查看答案:[用jQuery獲取元素列表](http://stackoverflow.com/questions/1227286/get-class-list-for-element-with-jquery)。 – Trylks
@Trylks太棒了!這實際上解決了我的問題,甚至更好的方法!謝謝! (但是,這是一個很長的路要提取這個名字) – Atadj