现在的位置: 首页 > 综合 > 正文

jQuery this揭秘

2019年10月31日 ⁄ 综合 ⁄ 共 2079字 ⁄ 字号 评论关闭

 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 matched 
DOM
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 the 
context
of 'this' changes
 when
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 on 
Firebug and
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的含义。

抱歉!评论已关闭.