删除一个子类并一次添加另一个类

时间:2019-02-03 13:56:29

标签: javascript

css文件

.clsA { ... }
.clsB { ... }
.clsC { ... }
...
...

js文件

var g = $('.gHead')

var res, last_key=''
var ca, cb, cc, cd, ....

ca = $('.clsA')
cb = $('.clsA')
cc = $('.clsA')
...
...

function nextV(a) {
    var len = a.length
    var choice = Math.floor(Math.random() * len) /* problem 1 */

    res = a.filter(function (elm) {
        return elm.key == a[choice].key
    })
    g.removeClass(res[0].key) /* problem 2 */
    last_key = res[0].key /* got key */
}

function changeIt() {
    var arr = []
    arr.push({key: 'ca', value: ca})
    arr.push({key: 'cb', value: cb})
    ...
    ...

    nextV(arr)

    if (res.length > 0) {
        g.addClass(res[0].key) /* working */
        console.log(g)
    }

    console.log('prevClass: '+ last_key) /* found prev added item */
}

$('.cng').on('click', function () {
    changeIt()
})

我希望.gHead每次点击.cng只能附加一个类。像:.gHead .clsA,下次点击时应为.gHead .clsB,依此类推。但是,我得到了:.gHead .clsA >> .gHead .clsA .clsB >> .gHead .clsA .clsB .clsC

问题1:
我想基于该数组arr的索引,而不是RandomChoice,使其成为LinearChoice。但是,我不想使用arr.indexOf()

问题2:
它-> g.removeClass(res[0].key)对输出没有影响。相对的g.addClass(...)几乎在工作!

4 个答案:

答案 0 :(得分:0)

您可以使用data()将上一个类存储在元素上,并在下次单击时检索该类以将其删除

由于您没有为完整示例提供足够的标记,因此这里是一个基本示例

const classes = ['a', 'b', 'c'];

function changeIt () {
  const $el = $(this),
    prevIndex = $el.data('prev'),
    // add one or go back to zero
    nextIndex = prevIndex + 1 < classes.length ? prevIndex + 1 : 0;

  if (prevIndex > -1) {
    // remove if previous exists
    $el.removeClass(classes[prevIndex])
  }
 // add the next class and store index on element
  $el.addClass(classes[nextIndex])
     .data('prev', nextIndex)

}

$('li').click(changeIt)
       .data('prev', -1)// initialize element data
.a{ color:red}
.b{color:blue}
.c{color:green}
li{padding:.5em}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul>
  <li>Click to change class</li>
  <li>Click to change class</li>
  <li>Click to change class</li>
  <li>Click to change class</li>
</ul>

答案 1 :(得分:0)

我稍微整理了一下代码,在这里您可以看到删除类不起作用,因为您是从nextV()返回后立即将其添加回去的。

js文件

var g = $('.gHead')

var ca, cb, cc, cd, ....

ca = $('.clsA')
cb = $('.clsA')
cc = $('.clsA')
...
...

var arr = [] // does not make sense to always recreate this
arr.push({key: 'ca', value: ca})
arr.push({key: 'cb', value: cb})
    ...

var choice = 0

function nextV() {
    choice = Math.floor(Math.random() * arr.length) /* problem 1 */
    // the filtering always leads to res being a single item array and res[0] being a[choice]
    g.removeClass(arr[choice].key) /* problem 2 */
}

function changeIt() {
    nextV()

    // if (res.length > 0) { // this is allways true in your code
    g.addClass(arr[choice].key) /* working */
}

$('.cng').on('click', function () {
    changeIt()
})

要线性遍历键,可以将choice初始化为arr.length-1而不是零,并在choice = (choice+1) % a.length中将选择计算为nextV而不是随机函数。

然后,您还可以使用g.removeClass(arr[(choice+arr.length-1)%arr.length].key)

在添加新的类(我认为您要做的“问题2”)之前删除上一类。

总结:根据您的描述,我不确定您的代码是否能达到您的期望,但是我希望这可以帮助您正确理解。

答案 2 :(得分:0)

如果要基于数组更改ONE元素上的css类(如charlietfl指出的),请执行以下操作:

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8">
        <title></title>
        <style>
          .gHead {
            width: 100px; height:100px;
          }
          .clsA {
            background: #000;
          }
          .clsB {
            background: #f00;
          }
          .clsC {
            background: #0f0;
          }
          .clsD {
            background: #00f;
          }
        </style>
      </head>
      <body>
        <div class="gHead clsA">
          Head
        </div>
        <script>
          var styles = ['clsA', 'clsB', 'clsC', 'clsD']
          var currentStyle = 0
          var gHead = document.querySelector('.gHead')

            function changeStyle () {

              if(currentStyle < styles.length - 1){

                currentStyle++
                gHead.classList.remove(styles[currentStyle-1])

              }else{

                currentStyle = 0
                gHead.classList.remove(styles[styles.length-1])
              }
              gHead.classList.add(styles[currentStyle])
            }
        </script>
        <button onClick="changeStyle()">change style</button>
      </body>
    </html>

答案 3 :(得分:0)

如果您有多个.gHead类的元素,则可以使用此

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8">
        <title></title>
        <style>
          .gHead {
            width: 100px; height:100px;
          }
          .clsA {
            background: #000;
          }
          .clsB {
            background: #f00;
          }
          .clsC {
            background: #0f0;
          }
          .clsD {
            background: #00f;
          }
        </style>
      </head>
      <body>
        <div class="gHead clsA">
          Head
        </div>

        <div class="gHead clsA">
          Head
        </div>

        <div class="gHead clsA">
          Head
        </div>
        <script>
          var styles = ['clsA', 'clsB', 'clsC', 'clsD']
          var currentStyle = 0
          var gHead = document.querySelectorAll('.gHead')
          function remove(x, reset) {
            reset ? x.classList.remove(styles[styles.length-1]) : x.classList.remove(styles[currentStyle-1])
          }
          function add(x) {
            x.classList.add(styles[currentStyle])
          }
          function newStyle () {

            if(currentStyle < styles.length - 1){

              currentStyle++

              for(var i = 0; i < gHead.length; i++){
                remove(gHead[i], 0)
                add(gHead[i])
              }

            }else{

              currentStyle = 0
              for(var i = 0; i < gHead.length; i++){
                remove(gHead[i], 1)
                add(gHead[i])
              }
            }

          }
        </script>
        <button onClick="newStyle()"></button>
      </body>
    </html>