"this"如何进行?语法工作? [英] How does the "this" syntax work?
问题描述
是这行
$(this).attr("id").replace("_button","");
相当于这个吗?
this.attr("id").replace("_button","");
推荐答案
由于this
始终包含对object of invocation
的引用,所以它实际上取决于在何处调用该代码.
since this
always contains a reference to the object of invocation
, it really depends where you call that code.
如果在jQuery event handler
中调用它,则this
是对DOM element
本身的引用,因此您需要通过调用$()
将其转换为jQuery对象,然后才能对其调用jQuery方法.反过来意味着
If you call this within a jQuery event handler
, this
is a reference to the DOM element
itself, so you need to translate it into a jQuery object by calling $()
before you can call jQuery methods on it. That in turn means
this.attr("id").replace("_button","");
在该处无法使用.
例如,如果您要编写一个插件方法,则this
已经 IS 一个jQuery object
(reference
),并且两行实际上都将执行相同的操作.当然,如果this
已经是jQuery object
,则您需要做额外的工作,然后尝试再次解析它.
If you're writting a plugin method for instance, this
already IS a jQuery object
(reference
) and both lines would actually do the same. Of course, if this
already is a jQuery object
you doing extra work, trying to parse it again.
示例:
$.fn.yourplugin = function(){
// this refers to a jQuery object
return this.each(function(i,v){
});
});
这篇关于"this"如何进行?语法工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!