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元素之前。暂未测!

  • 相关阅读:
    ios常见面试题
    UIButton 头文件常见属性和方法
    UILabel头文件常见属性
    UIButton 文档翻译(持续更新)
    UITextView
    iOS国际化
    55分钟学会正则表达式
    提示框的使用UIAlertController(UIAlertView和UIActionSheet二合一,包含通知中心的使用)
    macbook恢复Finder消失的个人收藏:桌面、文稿、下载、图片
    Socket
  • 原文地址:https://www.cnblogs.com/chig/p/12198048.html
Copyright © 2011-2022 走看看