标签:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script type="text/javascript"> window.onload = function (){ var obtn = document.getElementById("btn"); function fn(){ alert(this); } fn(); obtn.onclick = fn; } </script> </head> <body> <input type="button" name="btn" id="btn" value="按钮" /> </body> </html>
this指的是调用当前方法(函数)的对象,也可以理解为谁让函数运行,谁就是这个this.
var obtn = document.getElementById("btn"); obtn.onclick = function(){ this; }
很明显,调用当前匿名函数的对象为obtn
window.onload = function (){ var obtn = document.getElementById("btn"); function fn(){ this; } fn(); obtn.onclick = function(){ fn(); } }
而当obtn里面调用了另外一个函数,那么fn的对象仍然为window.
理解:
<script type="text/javascript"> window.onload = function (){ var abtn = document.getElementsByTagName("input"); for(var i = 0; i<abtn.length;i++){ abtn[i].onclick = function(){ this.style.backgroundColor = "yellow"; } } } </script> </head> <body> <input type="button" name="btn1" id="btn1" value="按钮" /> <input type="button" name="btn2" id="btn2" value="按钮" /> <input type="button" name="btn3" id="btn3" value="按钮" /> </body>
this指的是obtn对应的input标签
<script type="text/javascript"> window.onload = function (){ var abtn = document.getElementsByTagName("input"); var that = null; for(var i = 0; i<abtn.length;i++){ abtn[i].onclick = function(){ that = this; fn(); } } function fn(){ that.style.backgroundColor = "yellow"; } } </script> </head> <body> <input type="button" name="btn1" id="btn1" value="按钮" /> <input type="button" name="btn2" id="btn2" value="按钮" /> <input type="button" name="btn3" id="btn3" value="按钮" /> </body>
可以先定义一个空元素,通过把当前this所对应的对象保存到空元素中,然后在另外的一个函数中实现出来。
<script type="text/javascript"> window.onload = function (){ var abtn = document.getElementsByTagName("input"); var that = null; for(var i = 0; i<abtn.length;i++){ abtn[i].onclick = fn; } function fn(){ this.style.backgroundColor = "yellow"; } } </script> </head> <body> <input type="button" name="btn1" id="btn1" value="按钮" /> <input type="button" name="btn2" id="btn2" value="按钮" /> <input type="button" name="btn3" id="btn3" value="按钮" /> </body>
这是另外一种用法。
标签:
原文地址:http://www.cnblogs.com/running-wsnail/p/5631559.html