码迷,mamicode.com
首页 > 编程语言 > 详细

javascript:this的解释

时间:2016-08-01 23:37:22      阅读:444      评论:0      收藏:0      [点我收藏+]

标签:this有关知识

一、
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>

<script>

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

function fn1(){
	// this
}
// fn1();			this => window
// oDiv.onclick = fn1;			this => oDiv
/*
oDiv.onclick = function (){
	fn1();					fn1() 里的this => window
};

<div onclick="    this     fn1();      "></div>     fn1(); 里的 this 指的是 window
*/


// alert( this );		// object window

// window 是 JS “老大”
// window.alert( this );

function fn1(){
	alert( this );				// window
}
// fn1();
// window.fn1();
</script>

</head>

<body>

<input id="btn1" type="button" value="按钮" />

<input id="btn2" type="button" onclick=" fn1(); " value="按钮2" />

<script>
var oBtn = document.getElementById(‘btn1‘);
// oBtn.onclick = fn1;
oBtn.onclick = function (){
	// this
	fn1();
};
</script>

</body>
</html>

二、

<!DOCTYPE HTML>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<title>无标题文档</title>


<script>


/*

alert(this); window


fn1(this);

function fn1(obj){

obj => window

}


oDiv.onclick = function (){

this

fn1(this);

};

function fn1(obj){  obj => oDiv }

*/


window.onload = function (){

var aBtn = document.getElementsByTagName(‘input‘);

var that = null; // 空

for(var i=0; i<aBtn.length; i++){

/*

aBtn[i].onclick = function (){

// this.style.background = ‘yellow‘;

that = this;

fn1();

};

*/

aBtn[i].onclick = fn1;

}

function fn1(){

// this =>  window

// that.style.background = ‘yellow‘;

// this.style.background = ‘red‘;

}

};

</script>


</head>


<body>


<input type="button" value="按钮1" />

<input type="button" value="按钮2" />

<input type="button" value="按钮3" />


</body>

</html>


三、

<!DOCTYPE HTML>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

<title>无标题文档</title>

<style>

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>

window.onload = function (){

var aLi  = document.getElementsByTagName(‘li‘);

var that = null;

for( var i=0; i<aLi.length; i++ ){

aLi[i]. = function (){

that = this;

fn1();

};

aLi[i]. = function (){

this.getElementsByTagName(‘div‘)[0].style.display = ‘none‘;

};

}

function fn1(){

that.getElementsByTagName(‘div‘)[0].style.display = ‘block‘;

}

};

</script>

</head>


<body>


<ul>

<li>

  <div></div>

  </li>

<li>

  <div></div>

  </li>

<li>

  <div></div>

  </li>

</ul>


</body>

</html>


本文出自 “春天里!” 博客,谢绝转载!

javascript:this的解释

标签:this有关知识

原文地址:http://11180930.blog.51cto.com/11170930/1832905

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!