可能重复:
jQuery $(this) vs this
"this" 和 "$(this)" 有什么区别?
我如何知道使用哪一个?
相关的,我认为:
对于每个,您都有可选参数。 "i" 和 "this"(或"$(this)")有什么不同?
$('img').each(function(i) { ....code }
对比。
$('img').each(function() { ....code }
可能重复:
jQuery $(this) vs this
"this" 和 "$(this)" 有什么区别?
我如何知道使用哪一个?
相关的,我认为:
对于每个,您都有可选参数。 "i" 和 "this"(或"$(this)")有什么不同?
$('img').each(function(i) { ....code }
对比。
$('img').each(function() { ....code }
this
对象不会改变。它是函数的所有者。在大多数情况下,像这样简单地作为一个节点,并且您可以引用其所有属性,如this.className
(把它想象成使用document.getElementById
获取的节点或其他内容)。 它只是函数的“所有者”。
因此,您只需将this
对象传递给jQuery的$()
。
结论:如果要为当前节点使用jQuery函数,请使用$(this)
。但如果要访问对象自己的属性(例如.name
、className
、.id
),则只需使用this
。
this
的那句话有点误导。 - alex.each()
(例如$(".thing").each(...)
),那么最可能的是$(this).width()
,因为.width()
是jQuery方法。 - Joseph Mariklethis
总是相同的 this
。如果你把它放在 $()
中,你只是把它传递给 jQuery。 - Joseph Marikle$(this).on('click', function() { console.log(123); });
or
$('img').eq(i).on('click', function() { console.log(123); });
编辑2:以下是使用方法:
var sorter = {
sort: function() {
console.log('sorting');
},
requestSorting: function() {
this.sort();
}
}
sorter.requestSorting.bind(sorter);
this
在jQuery中一般指代DOM元素,例如HTMLSelectElement
。
使用jQuery函数重新包装它可以使您对其调用jQuery方法。
是否需要 $(this) 取决于您所处的上下文环境。
需要它的情况:
处理 jQuery 事件时 $(this) 作为触发事件的 DOM 元素传递,将 DOM 元素转换为 jQuery 对象
任何时候获取 DOM 元素 其他情况下,您拥有 DOM 元素(或对象)并希望将其转换为 jQuery 对象
不需要它的情况:
即使 this 是一个 jQuery 对象,使用 $(this) 也不会造成任何损害,因为 jQuery 只会返回相同的对象。
$( ".class" ).click( function () {
$( this ).load( "/path/to/file.html" );
} );
this
指的是 .class
div,当你点击它时,会将 file.html
的内容加载到该 div 中。.class
,就会将 file.html
加载到其中。