javascript:this的解釋

1、
<!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>

2、html

<!DOCTYPE HTML>ide

<html>函數

<head>ui

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

<title>無標題文檔</title>spa


<script>htm


/*對象

alert(this);windowip


fn1(this);utf-8

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>


3、

<!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>

相關文章
相關標籤/搜索