“this”这个词在jQuery中有什么作用

What does "this" word do in jQuery?

本文关键字:jQuery 什么 作用 this      更新时间:2023-09-26

所以,这里有一个问题

不能不知道什么时候我应该使用"这个"而不是类或id

如果你能展示例子 - 那将是非常棒的

谢谢

不能不知道什么时候我应该使用"这个"而不是类或id

通常,当您想要引用从事件处理程序中触发事件的元素时,可以执行此操作:

$(".foo").on("click", function() {
    var $el = $(this);           // `this` is the element that was clicked,
                                 // so `$(this)` gives you a jQuery wrapper
                                 // around just that one element.
                                 // But $(".foo") would give you a wrapper
                                 // around **all** .foo elements, not just the
                                 // one that was clicked.
    // ...
});

现场示例:

$(".foo").on("click", function() {
  var $el = $(this); // `this` is the element that was clicked
  $el.text("You've clicked this one");
});
<div class="foo">Not clicked yet</div>
<div class="foo">Not clicked yet</div>
<div class="foo">Not clicked yet</div>
<div class="foo">Not clicked yet</div>
<div class="foo">Not clicked yet</div>
<div class="foo">Not clicked yet</div>
<div class="foo">Not clicked yet</div>
<div class="foo">Not clicked yet</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

有时,当使用each$.each时会出现它,因为jQuery调用了每个方法的回调,this引用了该调用的元素:

$(".foo").each(function() {
    var $el = $(this);               // `this` is the element for this callback
    // ...
});

jQuery API 文档将告诉您何时在回调中将this设置为特定值。