js中的DOM对象和jQuery对象的比较

1. 二者的不同之处:

通过jQuery获取的元素是一个数组, 数组中包含着原生JS中的DOM对象。 

例如, 针对下面的一个div结构:

    <div id="Box"></div>
    <div class="box"></div>
    <div class="box"></div>

通过原生JS获取这些元素节点的方式是:

<script type="text/javascript">
        var myBox = document.getElementById("Box")          //通过id获取单个元素
        var boxArr = document.getElementsByClassName("box") //通过class获取的是伪数组
        var divArr = document.getElementsByTagName("div")   //通过标签获取的是伪数组
</script>

通过jQuery获取这些元素节点的方式:

   <script src="jquery.js"></script>
   <script type="text/javascript">
        <!--获取的是数组, 里面包含着原生JS中的DOM对象-->
        console.log($("#Box"));
        console.log($(".box"));
        console.log($("div"));
    </script>

结果显示为:

由于jQuery自带了css()方法,我们还可以直接在代码中给div设置css属性, 如下面所示:

        $("div").css({
            "width": "200px",
            "height": "200px",
            "background-color": "red",
            "margin-top": "20px"
        })

总结:

jQuery就是把DOM对象重新包装了一下, 让其具有了jQuery方法。

 

2. 二者的相互转换

(1)DOM对象转为jQuery对象:

$(JS对象);

(2)jQuery对象转为DOM对象:

jQuery对象[index];    //方式1 (推荐使用)

jQuery对象.get(index); //方式2

jQuery对象转换成DOM对象之后, 可以直接调用DOM提供的一些功能。 

        $("div")[1].style.backgroundColor = "yellow";
        $("div")[2].style.backgroundColor = "red";

总结:

  如果想要使用使用哪种方式设置属性或方法, 必须转换成该类型。

 

3. jQuery示例: 隔行换色

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>隔行换色</title>
    <script src="jquery.js"></script>
    <script>
        $(function () {
            var jQuery_li = $("li");
            for(var i=0; i<jQuery_li.length; i++){
                if(i % 2 == 0){
                    jQuery_li[i].style.backgroundColor = "yellow";
                }else {
                    jQuery_li[i].style.backgroundColor = "green";
                }
            }
        })
    </script>
</head>
<body>
    <ul>
        <li>This is the first line.</li>
        <li>This is the second line.</li>
        <li>This is the Third line.</li>
        <li>This is the fourth line.</li>
        <li>This is the fifth line.</li>
        <li>This is the sixth line.</li>
    </ul>
</body>
</html>

显示结果为:

 

posted @ 2018-08-17 17:09  _杨魏  阅读(1318)  评论(0编辑  收藏  举报