"this"语法如何工作?

Isa*_*bow 10 jquery

是这条线

$(this).attr("id").replace("_button","");
Run Code Online (Sandbox Code Playgroud)

相当于这一个?

this.attr("id").replace("_button","");
Run Code Online (Sandbox Code Playgroud)

jAn*_*ndy 9

因为this总是包含对一个参考object of invocation,它实际上取决于在那里你调用的代码.

如果您在电话本jQuery event handler,this是对参考DOM element本身,所以你需要通过调用把它翻译成一个jQuery对象$(),然后才能调用它的jQuery方法.这反过来意味着

this.attr("id").replace("_button","");
Run Code Online (Sandbox Code Playgroud)

不会在那里工作.

例如,如果您正在编写插件方法,则this已经是IS a jQuery object(reference),并且两条线实际上都是相同的.当然,如果你this已经jQuery object做了额外的工作,试着再次解析它.

例:

$.fn.yourplugin = function(){
     // this refers to a jQuery object
     return this.each(function(i,v){
     });
});
Run Code Online (Sandbox Code Playgroud)