【发布时间】:2011-04-10 18:34:59
【问题描述】:
jQuery 中的$(this) 和this 有什么区别,为什么它们有时给出相同的结果而有时表现不同?
【问题讨论】:
-
他们什么时候“给出相同的结果”?
标签: jquery jquery-selectors this
jQuery 中的$(this) 和this 有什么区别,为什么它们有时给出相同的结果而有时表现不同?
【问题讨论】:
标签: jquery jquery-selectors this
$(this) 使用 jQuery 功能包装 this。
例如,此代码将失败:
$('.someDiv').onClick(function(){
// this refers to the DOM element so the following line would fail
this.fadeOut(100);
});
所以我们将this 包装在 jQuery 中:
$('.someDiv').onClick(function(){
// wrap this in jQuery so we can use jQuery fadeOut
$(this).fadeOut(100);
});
【讨论】:
$(this) 使用 jQuery 函数装饰 this 指向的任何对象。典型的用例是this 引用一个 DOM 元素(例如,<div>)。然后,编写$(this) 允许您在<div> 上使用所有的jQuery API 函数。
如果 this 已经引用了一个 jQuery 对象——通常是一个 jQuery 装饰的 DOM 对象——那么调用 $(this) 将没有任何效果,因为它已经被装饰了。
【讨论】:
如果在当前上下文中 this 不是 jQuery 对象,则可以通过将其包裹在 $() 周围使其成为 jQuery 元素。当您的元素已经是 jQuery 表达式的结果时,this 在这种情况下已经是一个 jQuery 对象。所以在这种情况下,它们的工作方式相似
【讨论】:
为了让你更好地理解,给自己找一个调试器,比如谷歌浏览器,然后这样做..
$('a').click(function(){
console.log(this); //DO
console.log($(this)); //JO
});
这会告诉你有什么区别:)
【讨论】:
this 是一个 javascript 变量,每当您在附加到对象的函数中时创建。在这些情况下,this 指的是该对象。
$(this) 返回一个 jQuery 对象,您可以在该对象上调用 jQuery 函数,但仅适用于 this。
例如,如果您为所有锚点设置点击处理程序:
$('a').click(function() {
console.log(this.href) ;
}) ;
然后this,指的是锚点,点击事件(函数)被附加到。
【讨论】:
$(this) == 这个?有趣的。
这不能通过 DOM 事件传递。
【讨论】:
在 JavaScript 中,this 总是指正在执行的函数的“所有者”。使用 $(this) 只会包装所有者,以便所有 jQuery 操作都将被扩展并可供它使用。
考虑:
$links = $('#content a');
$links.click(function() {
link = this;
$link = $(this); //jQuery wrapped object.
alert(link.getAttribute('href'));
alert($link.attr('href')); //we can use the attr() function from jQuery
});
它们通常给出相同的结果,因为所有者是相同的,只是当它被 jQuery 包装时,它可以与 jQuery 函数一起操作。
【讨论】: