有问题的代码在这里:

var $item = $(this).parent().parent().find('input');

在变量名中使用美元符号的目的是什么,为什么不直接排除它呢?


当前回答

我要补充一点:

在chromium浏览器的开发控制台(还没有尝试过其他)中,$是一个原生函数,作用就像document一样。querySelector很可能是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对象的变量可以立即识别,代码更易于阅读,并消除了使用$()的双/多次换行。

这里有一个很好的短视频解释:https://www.youtube.com/watch?v=Acm-MD_6934

According to Ecma International Identifier Names are tokens that are interpreted according to the grammar given in the “Identifiers” section of chapter 5 of the Unicode standard, with some small modifications. An Identifier is an IdentifierName that is not a ReservedWord (see 7.6.1). The Unicode identifier grammar is based on both normative and informative character categories specified by the Unicode Standard. The characters in the specified categories in version 3.0 of the Unicode standard must be treated as in those categories by all conforming ECMAScript implementations.this standard specifies specific character additions:

美元符号($)和下划线(_)允许出现在IdentifierName中的任何位置。

进一步阅读可以在http://www.ecma-international.org/ecma-262/5.1/#sec-7.6上找到

Ecma国际是成立于1961年的行业协会,致力于信息通信技术(ICT)和消费电子产品(CE)的标准化。

我可能会补充说,使用它的jQuery可以让你做这样的事情,例如:

$.isArray(myArray);

美元符号在ecmascript 2015-2016中用作“模板文字”。 例子:

var a = 5;
var b = 10;
console.log(`Sum is equal: ${a + b}`); // 'Sum is equlat: 15'

下面是工作示例: https://es6console.com/j3lg8xeo/ 注意这个符号" ' ",它不是普通的引号。

你也可以在使用jQuery库时遇到$。

$ sign在正则表达式中表示行结束。

没有理由。也许编写代码的人来自PHP。它的效果与将其命名为“_item”或“item”或“item$$”相同。

作为一个后缀(如“item$”,发音为“items”),它可以表示一个可观察对象,如DOM元素,作为一种称为“芬兰符号”的约定,类似于匈牙利符号。