zoukankan      html  css  js  c++  java
  • js和jquery获取当前对象的子元素

    开发中经常遇到需要获取ul下的il对象,个人总结了jsjquery的方法。

    HTML片断:

        <ul class="box">
            <li>子元素1</li>
            <li>子元素2</li>
            <li>子元素3</li>
            <li>子元素4</li>
            <li>子元素5</li>
        </ul>

    先说说jquery的解决方案

            //获取li内容
            function getLi(obj,index){
                var child = obj.children("li").eq(index);
                return child.html();
            }
            $(function(){
                var c = 0;
                $(".box").click(function(){
                    if(c == 0){
                        console.log(getLi($(this),c));
                        c++;
                    }else if(c == 1){
                        console.log(getLi($(this),c));
                        c++;
                    }else if(c == 2){
                        console.log(getLi($(this),c));
                        c++;
                    }else if(c == 3){
                        console.log(getLi($(this),c));
                        c++;
                    }else if(c == 4){
                        console.log(getLi($(this),c));
                        c = 0;
                    }
                });
            });
    View Code

    $("elementName").children();获取当前对象的子元素(集合),若子元素有且只有一个就直接通过children()获取。若子元素有多个children()获取的就是一个集合,获取具体一个子元素就需要eq();获取。

    再来看看JavaScript的解决方案:

            var c = 0;
            var childArr = document.getElementsByClassName("box")[0].getElementsByTagName("li");
            document.getElementsByClassName("box")[0].onclick = function(){
                if(c == 0){
                        console.log(childArr[c].innerHTML);
                        c++;
                    }else if(c == 1){
                        console.log(childArr[c].innerHTML);
                        c++;
                    }else if(c == 2){
                        console.log(childArr[c].innerHTML);
                        c++;
                    }else if(c == 3){
                        console.log(childArr[c].innerHTML);
                        c++;
                    }else if(c == 4){
                        console.log(childArr[c].innerHTML);
                        c = 0;
                    }
            }
    View Code

    JS获取子元素用链式调用,DOM.getElement.._Parent.getElement.._Child;(dom.父元素.子元素)

    小结:个人觉得js的调用方式比jquery方便,通过链式调用便可获取元素子集。

  • 相关阅读:
    使用 Spring data redis 结合 Spring cache 缓存数据配置
    Spring Web Flow 笔记
    Linux 定时实行一次任务命令
    css js 优化工具
    arch Failed to load module "intel"
    go 冒泡排序
    go (break goto continue)
    VirtualBox,Kernel driver not installed (rc=-1908)
    go运算符
    go iota
  • 原文地址:https://www.cnblogs.com/MirageFox/p/5969753.html
Copyright © 2011-2022 走看看