为什么我必须使用$(this)? [英] Why do I have to use $(this)?
本文介绍了为什么我必须使用$(this)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
jQuery $(this)vs this
Possible Duplicate:
jQuery $(this) vs this
在jquery中,有时我发现在一个函数中我必须使用$(this)
,因为this
无法正常工作:
In jquery sometimes I find that within a function I have to use $(this)
because this
won't work:
var listItems = $('li');
listItems.each(function(index) {
$(this).css({
})
})
关于原因的任何想法?
Any ideas as to the reason why?
推荐答案
-
$()
是jQuery constructor
函数 -
this
是对DOM element of invocation
的引用
$()
is thejQuery constructor
functionthis
is a reference to theDOM element of invocation
因此,基本上,您是将DOM reference
转换为jQuery object
So basically, you're turning a DOM reference
into a jQuery object
在您的示例中,您也可以使用
In your example, you could also use
listItems.each(function(index, element){
$(element).css({
});
});
.. since .each()
将在其回调中同时传递索引和元素.
..since .each()
will pass both, index + element in its callback.
这篇关于为什么我必须使用$(this)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文