"this"如何进行?语法工作? [英] How does the "this" syntax work?

查看:65
本文介绍了"this"如何进行?语法工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是这行

$(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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆