angularjs1.x的directive中的link参数element见解

angular.module("APP",[])
    .directive("testDw",function () {
       return{
           restrict:"E",
           scope:"=",
           template: "<div class='a'><div class='b'> 123344</div></div>",
           link:function (scope,element,attrs) {
               console.log(element.length);  //1
               console.log(element);         //2
               console.log(element[0]);      //3
               console.log(element[0].firstChild);  //4
               console.log(element.children("div"));  //5
               console.log(element.children("div")[0]);   //6
               console.log(element[0].getElementsByClassName("a"));  //7
               element[0].getElementsByClassName("a")[0].style.backgroundColor="black";
               element[0].firstChild.style.backgroundColor="red";
           }
       }
    });

以上为指令中的代码

<!DOCTYPE html>
<html lang="en" ng-app="APP">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body >

<div><test-dw></test-dw></div>
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="app3.js"></script>
</body>
</html>

以上为html的代码

 结果:

1.结果是 length=1,可以看出element是一个有部分jquery dom对象属性的dom对象,且有数据特性;

2.从结果可以看出指向的是[test-dw],从图中可以看出element[0]=<test-dw>,length=1,_proto_为对象的内部原型(每个对象都会在其内部初始化一个属性,就是_proto_)

3.从结果可以看出 element[0]=<test-dw>

4.element[0].firstchild 为div块

5.element[0].children("div")不是一个div的具体块,它也和element一样是一个具有一个部分jquery dom对象属性的dom对象,且具有数据特性

6.element[0].children("div")[0]这个才是到了具体的div块 (它和element[0].firstchild一样,可以对比下)

7.注意:结果和5不一样,7是用原生的js写的,所以内部原型不同。

原文地址:https://www.cnblogs.com/liris/p/5985651.html