如何添加一个类列表,并且只在JavaScript中显示最后一个类

How to add a list of classes and only show the last one in JavaScript?

本文关键字:JavaScript 最后一个 显示 何添加 添加 一个 列表      更新时间:2023-09-26

我有一个函数,它调用添加到我的div中的随机数目的类:

htmlFields[i].classList.add(numbers[i]);

numbers[i]可以添加随机类:'one','two','three','four','five'

我的div已经有了'static''static2'类,可以像这样随机添加类:

<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);

显式删除所有其他随机类,或者使用setAttribute并重新添加静态类。

删除所有"随机"类:

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]);

不确定你所说的随机类到底是什么意思,以及你想在什么条件下添加其中一个类,但以下是如何在不丢失静态类的情况下添加类。

var elems = Array.prototype.slice.call(document.querySelectorAll('.static')),
    numbers = ['one','two','three','four','five'];
elems.forEach(function(elem, i) {
    elem.className = elem.className + " " + numbers[i];
});
<div class="static static2"></div>
<div class="static static2"></div>
<div class="static static2"></div>
<div class="static static2"></div>
<div class="static static2"></div>