我有一些lments,像这样:
<lment class="item-45 big top hold"></lment>
<lment class="item-46 big top grid"></lment>
<lment class="item-47 big top stop"></lment>
我可以使用以下方式选择它们:
lments = $('[class^="item"]');
但是我如何获得“45”、“46”和“47”?
我从这样的事情开始:
itsClass = lments[i].getAttribute('class');
我不知道从这里去哪里,但希望最终得到与此相同的结果:
lmentsItemNum = someExtractorFunction(itsClass);
最佳答案
由于您需要在开始时获取类名,因此您可以使用 map()
执行类似的操作
lments = $('[class^="item"]').map(function() {
return this.className.split(' ')[0].split('-')[1];
}).get();
console.log(lments);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<lment class="item-45 big top hold"></lment>
<lment class="item-46 big top grid"></lment>
<lment class="item-47 big top stop"></lment>
如果不是这种格式则
lments = $('[class*="item-"]').map(function() {
var a;
this.className.split(' ').forEach(function(v){
if(v.match(/^item-\d+$/))
a=v.split('-')[1];
});
if(a)
return a;
}).get();
console.log(lments);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<lment class="item-45 big top hold"></lment>
<lment class="item-46 big top grid"></lment>
<lment class="item-big top grid"></lment>
<lment class="item-47 big top stop"></lment>
关于javascript - 使用 JavaScript 或 jQuery 提取特定类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32598760/