jQuery this揭秘

本文详细解析了jQuery中this的两种主要解释:作为DOM元素和jQuery对象。通过实例代码展示了如何在不同场景下正确使用this,帮助开发者更好地理解和运用jQuery。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

jQuery this揭秘

this是什么?


In many object-oriented programming languages, this (or self) is a keyword which can be used in instance methods to refer to the object on which the currently executing method has been invoked.

在面向对象语言中,this(或self)被用于在实例方法中指向调用该方法的对象。


jQuery的this

There are really two main contexts of 'this' in jQuery. The first refers to a to a DOM element, and the second to a jQuery object.

在jQuery中this存在两种不同的解释。第一种指向一个DOM元素,第二种指向一个jQuery对象。

Example of this as a DOM element


将this作为DOM元素的实例

'this' is a DOM element when you are inside of a callback function (in the context of jQuery), for example, being called by the click, each, bind, etc. methods.


this在jQuery的回调函数,如click,each, bind等方法时是一个DOM元素。


$('a.newTarget').each(function() { // <- our anonymous callback
 // check the DOM attribute 'host' on this
 if (this.host != window.location.host) {
  // create a jQuery object using the current DOM element
  $(this).attr('target', '_new');
 }
});


Example of this as a jQuery object


将this作为jQuery对象的实例


'this' is a jQuery object when you are inside your own jQuery functions. Note that the result of a selector query (i.e. $('a') ) is a jQuery object, which is an array of the matchedDOM elements(imagine jQuery is an array with bells on).


当this用于你自己的jQuery对象时,this是一个jQuery对象。

注: 一个选择器查询,如$('a')的结果是一个jQuery对象,其实是由一组DOM元素组成的数组。


jQuery.fn.newTarget = function() {
 // 'this' is a jQuery object at this point - with all the jQuery functions

 return this.each(function() { // return so we don't break the chain
  // now we are inside of a jQuery function, the DOM element is the context
  // so 'this' has changed to become a DOM element.

  if (this.host != window.location.host) {
   $(this).attr('target', '_new');
  }
 });
};


Finishing up

结束语


This is far from comprehensive, but equally there's very little to the logic. So long as you remember thecontext of 'this' changeswhen moving in and out of object methods then you're on your way.


以上远不足以使你理解jQuery中this的用法。但是只要当你move int and out of 对象时谨记this改变的上下文,then you're on your way.


If you're still not sure, get your hands onFirebugand add 'console.log(this)' within your code to interrogate and understand what 'this' is at that point in your code.


如果你仍不确信,使用Firebug,添加‘console.log(this)’到你的代码中来查询并理解当前位置的this的含义。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值