this的指向及应用

时间:2022-04-10 06:46:17

this的指向:

 //this 指的是调用 当前方法 (函数) 的那个对象

 function fn1(){
this;
} //fn1(); this => window
//obj.onclick=fn1; this=>obj
//obj.onclick=function(){ this; } this=>window;

this的应用:

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style type="text/css">
*{margin: 0;padding: 0;}
ul,li{list-style: none;}
li { width:100px; height:150px; float:left; margin-right:30px; background:#f1f1f1; position:relative; z-index:1; }
div { width:80px; height:200px; background:red; position:absolute; top:75px; left:10px; display:none; }
</style>
<script type="text/javascript">
window.onload=function(){
var oUl=document.getElementById("ul1");
var aLi=oUl.getElementsByTagName("li"); for(var i=0;i<aLi.length;i++){
aLi[i].onmouseover=function(){
this.getElementsByTagName("div")[0].style.display="block";
};
aLi[i].onmouseout=function(){
this.getElementsByTagName("div")[0].style.display="none";
};
};
};
</script>
</head>
<body>
<ul id="ul1">
<li><div></div></li>
<li><div></div></li>
<li><div></div></li>
<li><div></div></li>
</ul>
</body>
</html>