动态通过添加数字来更改同一类的类名

时间:2017-08-01 23:19:02

标签: javascript classname

最后一个问题..如何动态地通过添加数字来更改相同乐器的类名?

<div class="score">
  <div class="system">
    <div class="stff_Flute"></div>
    <div class="stff_Flute"></div>
    <div class="stff_Clarinet"></div>
  </div>
  <div class="system">
    <div class="stff_Flute"></div>
    <div class="stff_Flute"></div>
    <div class="stff_Clarinet"></div>
  </div>
</div>

对此?...

<div class="score">
  <div class="system">
    <div class="stff_Flute_1"></div>
    <div class="stff_Flute_2"></div>
    <div class="stff_Clarinet"></div>
  </div>
  <div class="system">
    <div class="stff_Flute_1"></div>
    <div class="stff_Flute_2"></div>
    <div class="stff_Clarinet"></div>
  </div>
</div>

我有这段代码https://jsfiddle.net/7cLoxn29/1/,但有些不对劲......

1 个答案:

答案 0 :(得分:0)

我不是非常喜欢jQuery,所以我为你创建了一个vanilla JS解决方案(希望这没关系!):

let parents = document.querySelectorAll(".system")
parents.forEach((parent) => {
  let children = parent.querySelectorAll("div")
  children = Array.from(children).reduce((accumulator, current) => {
    if (current.className in accumulator) {
      accumulator[current.className].push(current)
    } else {
      accumulator[current.className] = [current]
    }
    return accumulator
  }, {})

  for (var key in children) {
    if (children[key].length > 1) {
      children[key].forEach((child, i, target) => {
        child.className = `${child.className}_${i+1}`
      })
    }
  }
})

请注意,这是ES2015 JS代码。

这是一个更新的小提琴:https://jsfiddle.net/7cLoxn29/5/