您的位置:首页 > Web前端 > JavaScript

javascript:this的解释

2016-08-01 12:03 113 查看
一、
<!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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  知识 this 有关