为什么在javascript变量的名称中使用$(美元符号)? [英] Why use $ (dollar sign) in the name of javascript variables?

查看:160
本文介绍了为什么在javascript变量的名称中使用$(美元符号)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

为什么javascript变量会以美元符号开头?

JQuery:&ndquo; var test”有什么区别?并且“ var $ test”

这两种方式有什么区别初始化变量?

What is the difference between this two ways of initializing variables?

var $val = 'something'

     OR

var val = 'something'

因为我认为它们是相同的。

as I see they are the same thing.

在这种情况下,可能 $ 只是变量中名称的一部分?
(在这种情况下它将成为一个毫无意义的问题:/)

Maybe in this case $ is only the part of name in variable? (it will become a meaningless question in that case:/)

谢谢

推荐答案

变量名称中的 $ 只是名称的一部分,但约定当变量表示jQuery对象时,用它来启动变量名。

The $ in the variable name is only part of the name, but the convention is to use it to start variable names when the variable represents a jQuery object.

var $myHeaderDiv = $('#header');
var myHeaderDiv = document.getElementById('header');

现在稍后在您的代码中,您知道 $ myHeaderDiv 已经是一个jQuery对象,所以你可以调用jQuery函数:

Now later in your code, you know the $myHeaderDiv is already a jQuery object, so you can call jQuery functions:

$myHeaderDiv.fade();



从DOM变量到jQuery变量:



To get from the DOM-variable to the jQuery variable:

var $myHeaderDiv = jQuery(myHeaderDiv); //assign to another variable
jQuery(myHeaderDiv).fade(); //use directly

//or, as the $ is aliased to the jQuery object if you don't specify otherwise:
var $myHeaderDiv = jQuery(myHeaderDiv); //assign
$(myHeaderDiv).fade(); //use



从jQuery变量到DOM变量。



To get from the jQuery variable to the DOM-variable.

var myHeaderDiv = $myHeaderDiv.get(0);

这篇关于为什么在javascript变量的名称中使用$(美元符号)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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