tab-switch 样式的添加 与 tab元素样式的切换

要点:

1.多个div类名相同情况下添加class样式

2.siblings() 方法返回被选元素的所有同级元素。DOM 树:该方法沿着 DOM 元素的同级元素向前和向后遍历。

3.利用索引,只添加当前等于该索引的.tab-switch-item,其他通过遍历siblings()移除.on样式

方式一:

$(document).ready(()=>{
   $('.tab-switch-item').on('click',function(){
      //通过 .index()方法获取元素下标,从0开始,赋值给某个变量
          var _index = $(this).index();
      //让内容框的第 _index个显示出来,其他的被隐藏
          $('.tab-switch-item').eq(_index).addClass('on').siblings().removeClass('on')
      //改变选中时候的选项框的样式,移除其他几个选项的样式
        //  $(this).addClass('on').siblings().removeClass('on');

         
   })
})
 

方式二:

$(document).ready(()=>{
   $('.tab-switch-item').on('click',function(){
      //通过 .index()方法获取元素下标,从0开始,赋值给某个变量
          var _index = $(this).index();
      //让内容框的第 _index个显示出来
          $('.tab-switch-item').eq(_index).addClass('on')
      //改变选中时候的选项框的样式,移除其他几个选项的样式      
  $(this).addClass('on').siblings().removeClass('on');

         
   })
})
 
注意:
$(this).addClass("on").siblings().removeClass("on").children('.tab).html() 的解释
该元素增加一个类on同时它的兄弟元素去掉on类,并获取它的子元素.tab里的html内容;
siblings()起作用是筛选给定的同级同类元素(不包括给定元素本身)

运用:页面标签切换(切记负责点击切换的tab标签的DIV不要与负责显示内容的DIV为同级元素,要不然标签也会被一同hide())
class为.tab-switch-item的div标签 为三个、多个class为.level-box的DIV切换,(蓝色下划线class样式为.on)
$(document).ready(function(){
        $(".tab-switch-item").click(function(){
        //通过 .index()方法获取元素下标,从0开始,赋值给某个变量
            var index = $(this).index();
        //让内容框的第 index 个显示出来,其他的被隐藏
            $(".level-box").eq(index).show().siblings().hide();
        //改变选中时候的选项框的样式,移除其他几个选项的样式
        $(this).addClass("on").siblings().removeClass("on");
        });
    });

原文地址:https://www.cnblogs.com/2Octobering/p/13052341.html