我有一个函数,可以调用添加到我的 div 中的随机数量的类:
htmlFields[i].classList.add(numbers[i]);
numbers[i]
可以添加随机类:'one','two','third','four',' Five'
我已经有 'static'
,'static2'
类的 div 会像这样添加随机类:
<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() 方法,但它删除了静态类。
那么我怎样才能只添加最后一个“随机类”并同时保留静态类呢?
最佳答案
在调用 setAttribute 之前,您需要在函数中将当前类存储在变量中并添加随机数类,如下代码所示:
var currentClass = htmlFields[i].getAttribute('class');
currentClass += " " + numbers[i];
htmlFields[i].setAttribute('class', currentClass);
关于javascript - 如何在 JavaScript 中添加类列表并仅显示最后一个类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33896741/