[英]Do I need to put a dollar before variable names with javascript?
I have the following code: 我有以下代码:
var formSubmitHandler = function (link, form) {
//e.preventDefault();
var $form = form;
var val = $form.valid();
var action = $(form).data('action');
var entity = $(form).data('entity');
Do I need the line "var $form = form"? 我需要“var $ form = form”这一行吗? Can I just later on do "var val = form.valid(); ?
我可以稍后再做“var val = form.valid();?
It's not my code so I am wondering why the developer added the $ before the form and assigned it? 这不是我的代码所以我想知道为什么开发人员在表单之前添加$并分配它?
Update: 更新:
Thanks for all your replies. 感谢你的回复。 If as has been said it's just to indicate that it's a jQuery variable then could I just remove that line by changing the function parameters to (link, $form) ?
如果已经说过它只是表明它是一个jQuery变量那么我可以通过将函数参数更改为(link,$ form)来删除该行吗?
$
and jQuery
are basically the jQuery instance. $
和jQuery
基本上就是jQuery实例。
It's good to understand that $( < place something here >)
is a jQuery function call and $your_variable_name
is just a variable with a dollar. 很高兴理解
$( < place something here >)
是一个jQuery函数调用, $your_variable_name
只是一个带有美元的变量。
Some people use $
in their own variables to indicate that it is a jQuery object. 有些人在自己的变量中使用
$
来表示它是一个jQuery对象。 With this naming convention, your source code would like this. 有了这个命名约定,您的源代码就是这样的。
var formSubmitHandler = function (link, form) {
var $form = $(form);
var val = $form.valid();
var action = $form.data('action');
var entity = $form.data('entity');
No, you don't have to use the $
sign. 不,你不必使用
$
符号。 It's just an aesthetic choice usually. 这通常只是一种美学选择。
In your example code above, the function's argument is named form function (link, form)
. 在上面的示例代码中,函数的参数名为form
function (link, form)
。 Inside the function, the new variable being declared has a $
to it so as to distinguish it from the argument variable form
. 在函数内部,声明的新变量有一个
$
,以便将它与参数变量form
区分开来。
That is not neccessary. 这不是必要的。 The dollar sign before a variable is most of the times used as an indication it is a JQuery variable.
变量之前的美元符号大部分时间用作指示它是JQuery变量。 JQuery uses the dollar sign as a shortcut.
JQuery使用美元符号作为快捷方式。 Using it in a variable name has no extra meaning other than the aesthetic meaning for the developer that it is a JQuery object.
在变量名中使用它没有额外的意义,除了开发人员的美学意义,它是一个JQuery对象。
It has become best practice to use the $ sign to help you distinguish between Javascript variables representing regular DOM elements (and every other data type) and variables that hold a reference to a jQuery object. 最佳实践是使用$符号来帮助您区分表示常规DOM元素(和其他所有数据类型)的Javascript变量以及包含对jQuery对象的引用的变量。 For the latter you use the $ sign.
对于后者,您使用$符号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.