zoukankan      html  css  js  c++  java
  • JQ 遍历元素并给相应元素增加class

    应用帝国后台做公共模板时,需要公共导航栏点击后,加载到对应的栏目列表,同时该栏目导航项添加背景class

    思路:使用location.href获取到当前页链接,使用split切割获取的链接字符串,使用切割后得到的关键词匹配对应栏目class,遍历该class,同时给该class增加对应样式

    重点:1.location.href

               2.str.split('syb')

               3.$el.each(function(){})

    <div class="menu_scroll">
            <div class="menu_items">
                   <div class="item_cell active" data-url="index">
                        <a href="/" data-title="首页">首页</a>
                   </div>
                   <div class="item_cell yys" data-url="yys">
                        <a href="/yys/" data-title="应用">应用</a>
                   </div>
                   <div class="item_cell yxs" data-url="yxs">
                         <a href="/yxs/" data-title="游戏">游戏</a>
                   </div>
                   <div class="item_cell zts" data-url="zts">
                         <a href="/zts/" data-title="专题">专题</a>
                   </div>
                   <div class="item_cell zxs" data-url="zxs">
                         <a href="/zxs/" data-title="资讯">资讯</a>
                    </div>
                    <div class="item_cell jcs" data-url="jcs">
                         <a href="/jcs/" data-title="教程">教程</a>
                    </div>
                    <div class="item_cell hots" data-url="hots">
                         <a href="/hots/" data-title="热门标签">热门</a>
                    </div>
            </div>
    </div>
    
    <script type="text/javascript">
     $(".item_cell").removeClass('active');
            const localUrl= location.href;//获取当前页链接
            console.log(localUrl);                
                    var clsDatArr =localUrl.split("/");//切割链接组成数组
                    var clsNam = clsDatArr[3];获取关键字符
                    console.log(clsNam);
    $(function(){
       $(".item_cell").each(function(){
         if($(this).hasClass(clsNam)){
              $(this).addClass('active')
         }
       });
    });            
    </script>

    注意:需要在function中增加点击首页时候,获取关键字符为空的情况,应该预先判断是否为空,加在遍历li元素之前。暂未测!

  • 相关阅读:
    HDU-1225 Football Score
    HDU-3854 LOOPS
    HDU-3863 No Gambling
    poj-2096 Collecting Bugs
    HDU-4336 Card Collector
    HDU-4405 Aeroplane chess
    2010上交:最小面积子矩阵
    VijosP1443:银河英雄传说
    VijosP1250:分组背包
    Vijos1221:神秘的配方
  • 原文地址:https://www.cnblogs.com/chig/p/12198048.html
Copyright © 2011-2022 走看看