有问题的代码在这里:

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

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


当前回答

$符号是变量和函数的标识符。

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

其他回答

我要补充一点:

在chromium浏览器的开发控制台(还没有尝试过其他)中,$是一个原生函数,作用就像document一样。querySelector很可能是JQuery $的别名

在你的例子中,$除了作为名称的一个字符外没有任何特殊的意义。

然而,在ECMAScript 6 (ES6)中,$可以表示模板文字

var user = 'Bob'
console.log(`We love ${user}.`); //Note backticks
// We love Bob.

美元符号就像一个普通的字母或下划线(_)。它对解释器没有特别的意义。

与许多类似的语言不同,Javascript中的标识符(如函数名和变量名)不仅可以包含字母、数字和下划线,还可以包含美元符号。它们甚至可以以美元符号开头,或者只由美元符号组成,没有其他符号。

因此,$在Javascript中是一个有效的函数或变量名。

为什么要在标识符中使用美元符号?

该语法并没有真正强制在标识符中使用美元符号的任何特定用法,因此取决于您希望如何使用它。在过去,通常建议只在生成的代码中以美元符号开始标识符——也就是说,不是手工而是由代码生成器创建的代码。

然而,在你的例子中,情况似乎并非如此。看起来好像有人只是为了好玩才在开头放了一个美元符号——也许他们是PHP程序员,出于习惯才这么做的,或者别的什么。在PHP中,所有变量名前面都必须有一个美元符号。

There is another common meaning for a dollar sign in an interpreter nowadays: the jQuery object, whose name only consists of a single dollar sign ($). This is a convention borrowed from earlier Javascript frameworks like Prototype, and if jQuery is used with other such frameworks, there will be a name clash because they will both use the name $ (jQuery can be configured to use a different name for its global object). There is nothing special in Javascript that allows jQuery to use the single dollar sign as its object name; as mentioned above, it's simply just another valid identifier name.

    let $ = "Hello";
    let $$ = "World!";
    let $$$$$$$$$$$ = $ + " " + $$;
    alert($$$$$$$$$$$);

这将显示一个“Hello World!”警告框。

正如您所看到的,$只是JavaScript标识符或变量名的一个普通字符。事实上,您可以使用大量Unicode字符作为变量名,使其看起来像美元或其他货币符号!

注意,$符号也被用作jQuery名称空间/库的引用:

$("p").text("I am using some jquery");

// ...is the same as...

jQuery("p").text("I am using some jquery");

$也用于新的模板文字格式,使用JavaScript ES6/2015版本支持的字符串插值:

var x = `Hello ${name}`;

使用美元符号在JavaScript中并不常见,但是 专业程序员经常使用它作为main的别名 函数在JavaScript库中。 例如,在JavaScript库jQuery中,主函数$ 用于选择HTML元素。jQuery $("p");意思是“全选” P个元素。

通过https://www.w3schools.com/js/js_variables.asp