我有一个函数,它调用添加到div中的随机数量的类:
htmlFields[i].classList.add(numbers[i]);numbers[i]可以添加随机类:'one','two','three','four','five'
我的'static2'已经有了'static',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()方法,但它删除了静态类。
那么,我如何才能只添加最后一个“随机类”,同时保留静态类呢?
发布于 2015-11-24 23:10:03
在调用setAttribute之前,您需要在函数中将当前类存储在variable中,并添加随机数类,如下所示:
var currentClass = htmlFields[i].getAttribute('class');
currentClass += " " + numbers[i];
htmlFields[i].setAttribute('class', currentClass);发布于 2015-11-24 22:54:58
要么显式删除所有其他随机类,要么使用setAttribute并重新添加静态类。
发布于 2015-11-24 22:58:29
删除所有的“随机”类:
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]);https://stackoverflow.com/questions/33896741
复制相似问题