jQuery $(this)和’this’的区别
在本文中,我们将学习jQuery $(this)和’this’的区别。
this关键字: 在JavaScript中,this关键字用于引用它所属的对象。this存储的值是JavaScript程序的当前执行上下文。因此,在函数内部使用this时,this的值会根据函数的定义方式、调用方式和默认执行上下文而改变。
示例1: 我们将在一个对象方法中使用this,它指向对象的所有者。
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<!-- using jQuery library -->
<script src=
"https://code.jquery.com/jquery-git.js">
</script>
</head>
<body>
<p>The object's value for name: </p>
<p id="paraID"></p>
<script>
const obj = {
name: "hrithik",
roll: 36,
mydata: function () {
return this.name;
}
}
document.getElementById("paraID")
.innerHTML = obj.mydata();
</script>
</body>
</html>
输出:
The object's value for name:
hrithik
示例2: 我们将在事件处理程序中使用 this 关键字,它指的是调用事件的元素。
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<!-- using jQuery library -->
<script src=
"https://code.jquery.com/jquery-git.js">
</script>
</head>
<body>
<p id="clickme">
<b> Click this to change color.</b> <br>
</p>
<script>
$("#clickme").click(function () {
this.style.color = "green"
})
</script>
</body>
</html>
输出:
$(this): 它也指的是它所属的对象。基本上,它们是一样的。但是当 this 关键字在 $() 内使用时,它变成了一个 jQuery 对象,现在我们可以在这个方法上使用 jQuery 的所有属性。
示例:
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<!-- using jQuery library -->
<script src=
"https://code.jquery.com/jquery-git.js">
</script>
</head>
<body>
<b>
<p>Click to change color</p>
</b>
<p>GeekForGeeks</p>
<script>
("p").click(function () {
(this).css("color", "red");
});
</script>
</body>
</html>
输出:
这个和$(this)之间的区别
this关键字 是对调用的DOM元素的引用。我们可以在上面调用所有的DOM方法。
$() 是一个jQuery构造函数,在 $(this) 中,我们只是把 this 作为参数传递,以便我们可以使用jQuery函数和方法。
示例1: 下面的代码不起作用,因为我们在DOM元素上调用了一个jQuery方法。请参考输出结果以了解更多详情。隐藏操作不会发生。
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<!-- using jquery library -->
<script src=
"https://code.jquery.com/jquery-git.js">
</script>
</head>
<body>
<p class="div1">
Hello
</p>
<script>
$(".div1").click(function ()
{
// this refers to the DOM element
// so the following line would fail
this.hide();
});
</script>
</body>
</html>
输出:
示例2: 这段代码工作正常,因为我们已经将 this 实现为$(),现在它成为了一个jQuery对象。
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<!-- using jquery library -->
<script src=
"https://code.jquery.com/jquery-git.js">
</script>
</head>
<body>
<p class="div1">
Hello
</p>
<script>
(".div1").click(function () {
// this refers to the DOM element
//so the following line would fail
(this).hide();
});
</script>
</body>
</html>
输出:
this与$(this)之间的区别
this | $(this) |
---|---|
它指的是DOM元素 | 它也指的是DOM元素。 |
this 是以原生方式使用的。 | this 被放在$()中,它变成了一个jQuery对象。 |
我们可以在它上面调用所有DOM方法,但无法调用jQuery方法。 | 我们可以在它上面调用所有jQuery方法和函数,但无法调用DOM方法。 |
this 只有通用JavaScript功能。 | 通过使用 $(this) ,你为该对象启用了jQuery功能。 |