首页 > 技术文章 > js和jquery获取当前对象的子元素

MirageFox 2016-10-17 14:46 原文

开发中经常遇到需要获取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方便,通过链式调用便可获取元素子集。

推荐阅读