当我们在使用jQuery的时候,给某个标签绑定事件,会发现事件函数里面有个“this”,比如如下代码:
$("#a").click(function(){
$(this).hide();
});
这个this具体指什么了,我们不妨亲自动手检测一下,运行如下代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="../scripts/jquery.js" type="text/javascript"></script>
<script>
$(function(){
$("#a").click(function () {
// window.alert("click");
// window.alert(this);
console.log(this);
var $a=$("#a");//jQuery对象
var b=document.getElementById("a");//DOM对象
console.log($a);
console.log(b);
console.log(this===$a);
console.log(this===b);
console.log($a===b);
});
});
</script>
</head>
<body>
<div id="a">clickme</div>
</body>
</html>
结果:
由此可见,this指向的就是触发这个事件的DOM对象,而非jQuery对象,所以我们在事件内部使用this的时候,需要通过$(this)方法将DOM对象转化为jQuery对象,才能使用jQuery中的方法。