jquery this 和 $this 区别实验
很多人弄不清楚 再query 函数下 $this 和 this 的区别, 所以我们就来做个实验给大家看吧:
HTML 和测试的JS, 很简单!
<html> <head> <script type="text/javascript" src="jquery-3.3.1.min.js"></script> <script type="text/javascript" src="test.js"></script> <title>test</title> </head> <body> <p id="p1">If you click on me, I will disappear.</p> <p>Oo.</p> </body> </html>
$(document).ready(function(){
$("p").click(function(){
console.log($(this));
console.log(this);
console.log(this === $("#p1")[0]);
this.innerHTML= "New text1!";
//$("#p1")[0].innerHTML= "New text2!";
});
});
首先我们看看 点击 p1 段落后的输出
w.fn.init [p#p1]
test.js:4 <p id="p1">New text1!</p>
test.js:5 true
我们可以清晰的看到:
1. $(this) 是jquery 对象,有了他,我们可以用Jquery 定义的方法进行元素操作。
2. this 是指向了DOM 对象; 从Jquery 实现方式得知 $("#p1")[0] 是Jquery DOM 对象, this 和它是相等的, true
3. this 直接调用了 DOM 对象的方法。
这个测试很简单,说明了 this 指向的是DOM 对象,而$(this) 是 Jquery wrapper 对象。

浙公网安备 33010602011771号