关于 jq 的$(this)与 js 的 this 的联系与区别

区别

指向的对象不同:
this 指向 js 对象,对应js对象的属性和方法;
$(this) 指向 jquery 对象, 对应其属性和方法.

联系

  <div class="iconDiv"></div>

  function testFunction() {
    $('.iconDiv').click(function() {
      console.log(this); //返回事件绑定的 dom 节点
      console.log($(this)); //返回事件绑定的 jquery对象
      console.log($(this)[0] == this); //true
    });
  }
  testFunction();

console.log($(this)[0] == this);可以看出,在事件绑定的函中,$(this)[0]和 this 之间是可以相互转换的.

关于 $(this)应用的注意点:

$(this)在 jquery 中一般应用于事件绑定的函数中.这里应注意:

运行出错:

$('.player .controls .progressBar').mousedown(function(e) {
  progressMove(e);
});

function progressMove(e) {
  var updateTime = (e.offsetX / $(this)[0].offsetWidth) * playStatus.currentTotalTime;
  console.log($(this));//返回jquery的 Window对象
  //原因是$(this)不是处于事件绑定的函数中,而是在函数的函数中,因此在触发事件时,并不是指向目标对象
  $('#audio')[0].currentTime = updateTime;
}

运行正确:

$('.player .controls .progressBar').mousedown(function(e) {
  progressMove(e);
});

function progressMove(e) {
  var updateTime = (e.offsetX / $('.player .controls .progressBar')[0].offsetWidth) * playStatus.currentTotalTime;
  console.log(this);//✅ 返回一个预期结果
  $('#audio')[0].currentTime = updateTime;
}

或者

$('.player .controls .progressBar').mousedown(function(e) {
  var updateTime = (e.offsetX / $(this)[0].offsetWidth) * playStatus.currentTotalTime;//❗️这里的 $(this)指向事件绑定的对象
  $('#audio')[0].currentTime = updateTime;
});

总之,$(this)只有应用于在事件绑定的函数中,才能指向事件绑定的目标对象.若是位于绑定函数中的函数作用域,则无法指向目标对象.

posted @ 2020-08-13 20:24  EzenLee  阅读(712)  评论(0)    收藏  举报