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

时间:2016-03-18 12:34:38

标签: javascript jquery

所以,这是问题

当我应该使用“this”而不是class或id

时,我无法理解

如果你可以展示例子 - 这将是非常棒的

由于

1 个答案:

答案 0 :(得分:1)

  

当我应该使用&#34时,我无法理解这个"而是类或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>
&#13;
&#13;
&#13;

有时,在使用each$.each时会出现这种情况,因为jQuery使用this调用每个方法的回调来引用该调用的元素:

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

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