jQuery:为什么在变量名前加$? [英] jQuery: Why prepend a $ to variable name?

查看:361
本文介绍了jQuery:为什么在变量名前加$?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习jQuery,我在一个示例中碰到了这一行.

I am trying to learn jQuery and I came across this line in an example.

var $title = $(tag).attr('title');

有人可以告诉我$title中的前缀$是什么.

Can someone please tell me what the prepended $ is for in $title.

如果仅将$title替换为title,该示例似乎可以正常工作.

The example seems to work fine if I replace $title with just title.

我知道这可能是一个愚蠢的问题,但是浪费时间搜索"$的目的"

I understand this is probably a stupid question but it is a waste of time googling for "purpose of $"

非常感谢.

推荐答案

它不意味着"任何东西. $字符是Javascript变量名称中的合法字符.

It doesn't "mean" anything. The $ character is a legal character in Javascript variable names.

但是,有一种约定(不是通用的),即使用$作为任何指向jQuery选择的变量的前缀.

However, there is a convention (which isn't universal) of using $ as a prefix to any variable that points to a jQuery selection.

您举一个例子:

var $title = $(tag).attr('title');

根据约定,这是对$字符的错误使用. $title是字符串,而不是jQuery选择.

This is a bad use of the $ character, according to this convention. $title is a string, not a jQuery selection.

这将是该字符的正确用法:

This would be a correct use of the character:

var $el = $(tag);
var title = $el.attr('title');


否则,$字符盛行的主要原因是它在PHP中是必需的,而jQuery和PHP程序员之间有很大的重叠.


Otherwise, a big reason for the prevalence of the $ character is that it is mandatory in PHP, and there is a big overlap between jQuery and PHP programmers.

这篇关于jQuery:为什么在变量名前加$?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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