【问题标题】:Removing all classes in a container with javascript使用javascript删除容器中的所有类
【发布时间】:2021-11-13 05:55:51
【问题描述】:

我正在尝试删除父元素中的所有类,结构如下所示

<div id="middleCol">
  <section class="toggleSection" id="step1" v-on:click="toggleStep($event)" ref="step1">
    <small>Step 1</small>
    <h5>Flight Details</h5>
  </section>

  <section class="toggleSection"  id="step2" v-on:click="toggleStep($event)" ref="step2">
    <small>Step 2</small>
    <h5>Traveler Info</h5>
  </section>

  <section class="toggleSection"  id="step3" v-on:click="toggleStep($event)" ref="step3" >
    <small>Step 3</small>
    <h5>Payment</h5>
  </section>
</div>

基本上这些是选项卡,我只想一次将一个活动类应用于一个 div,我的计划是删除所有类,然后将活动类添加到使用事件单击的任何选项卡,但我收到错误其他子元素上的 className 属性不存在,该函数可以添加类而不是删除它们,我已经看到了一些 jquery 解决方案,但我希望找到一个普通的解决方案

任何帮助表示赞赏:)

这是我要使用的功能

function toggleActive(event){
  let element = event.currentTarget
  let parent = element.parentNode.children;
  console.log(element)
  console.log(parent)
           
  for (let child in parent){
    parent[child.value].className = ''
  }
  element.classList.add("toggleSectionActive");
}

【问题讨论】:

  • 不过,您显示的结构中没有类。最好展示一个示例,说明您将从什么开始以及您希望以什么结束,并使用您已经编写的代码来尝试实现这一目标。
  • 谢谢,我已经更新了我正在使用的相关 vue 模板代码的 sn-p
  • 如果你使用 Vue,我建议使用 Vue 的类绑定,让 Vue 决定每个部分使用哪些类,而不是手动更改它们vuejs.org/v2/guide/class-and-style.html,他们甚至显示了@的示例987654324@班级

标签: javascript css vue.js class


【解决方案1】:

尝试绑定类并使用 v-for for 部分:

new Vue({
  el: '#demo',
  data(){
    return {
      toggled: 0,
      sections: [
        {id: 0, name: 'Step 1', desc: 'Flight Details'},
        {id: 1, name: 'Step 2', desc: 'Traveler Info'},
        {id: 2, name: 'Step 3', desc: 'Payment'}
      ]
    }
  },
  methods: {
    toggleStep(id){
      this.toggled = id
    }
  }
})
.active {
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <div id="middleCol">
    <section :class="section.id === toggled && 'active'" v-for="section in sections" :key="section.id" @click="toggleStep(section.id)">
      <small>{{ section.name }}</small>
      <h5>{{ section.desc }}</h5>
    </section>
  </div>
</div>

【讨论】:

  • 谢谢,这帮我搞砸了 :) 我一直在关注 vbind 示例,试图找出答案,感谢您为我布置了正确的演示
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-06
  • 1970-01-01
  • 2010-11-28
  • 2016-01-19
  • 1970-01-01
  • 1970-01-01
  • 2013-08-26
相关资源
最近更新 更多