有问题的代码在这里:
var $item = $(this).parent().parent().find('input');
在变量名中使用美元符号的目的是什么,为什么不直接排除它呢?
有问题的代码在这里:
var $item = $(this).parent().parent().find('input');
在变量名中使用美元符号的目的是什么,为什么不直接排除它呢?
当前回答
使用美元符号在JavaScript中并不常见,但是 专业程序员经常使用它作为main的别名 函数在JavaScript库中。 例如,在JavaScript库jQuery中,主函数$ 用于选择HTML元素。jQuery $("p");意思是“全选” P个元素。
通过https://www.w3schools.com/js/js_variables.asp
其他回答
变量中的'$'对于解释器来说没有任何特殊意义,就像下划线一样。
据我所知,许多使用jQuery的人(在我看来,您的示例代码就是这样的)倾向于在包含jQuery对象的变量前面加上$,这样它们就很容易被识别,不会与整数混淆。
jQuery中的美元符号函数$()是一个经常使用的库函数,因此最好使用较短的名称。
在使用jQuery时,使用$符号作为变量名的前缀只是一种惯例;它是完全可选的,仅用于指示变量保存jQuery对象,如示例中所示。
这意味着当需要在对象上调用另一个jQuery函数时,您不需要再次将它包装在$()中。例如,比较这些:
// the usual way
var item = $(this).parent().parent().find('input');
$(item).hide(); // this is a double wrap, but required for code readability
item.hide(); // this works but is very unclear how a jQuery function is getting called on this
// with $ prefix
var $item = $(this).parent().parent().find('input');
$item.hide(); // direct call is clear
$($item).hide(); // this works too, but isn't necessary
使用$前缀,已经包含jQuery对象的变量可以立即识别,代码更易于阅读,并消除了使用$()的双/多次换行。
使用美元符号在JavaScript中并不常见,但是 专业程序员经常使用它作为main的别名 函数在JavaScript库中。 例如,在JavaScript库jQuery中,主函数$ 用于选择HTML元素。jQuery $("p");意思是“全选” P个元素。
通过https://www.w3schools.com/js/js_variables.asp
我要补充一点:
在chromium浏览器的开发控制台(还没有尝试过其他)中,$是一个原生函数,作用就像document一样。querySelector很可能是JQuery $的别名
$符号是变量和函数的标识符。
https://web.archive.org/web/20160529121559/http://www.authenticsociety.com/blog/javascript_dollarsign
它清楚地解释了美元符号的意义。
下面是另一种解释:http://www.vcarrer.com/2010/10/about-dollar-sign-in-javascript.html