“ $”符号在 jQuery 或 JavaScript 中是什么意思?

可能的复制品:
在 JavaScript 中“ $”符号的含义是什么

为什么我们在 jQuery 和 JavaScript 中使用美元($)符号? 我总是在我的剧本里放一美元,但是我不知道为什么。

举个例子:

$('#Text').click(function () {
$('#Text').css('color', 'red')
});

当你点击它的时候,它只是改变了文本的颜色,但是它证明了我的观点。

146741 次浏览

In JavaScript it has no special significance (no more than a or Q anyway). It is just an uninformative variable name.

In jQuery the variable is assigned a copy of the jQuery function. This function is heavily overloaded and means half a dozen different things depending on what arguments it is passed. In this particular example you are passing it a string that contains a selector, so the function means "Create a jQuery object containing the element with the id Text".

The $ symbol simply invokes the jQuery library's selector functionality. So $("#Text") returns the jQuery object for the Text div which can then be modified.

The $ is just a function. It is actually an alias for the function called jQuery, so your code can be written like this with the exact same results:

jQuery('#Text').click(function () {
jQuery('#Text').css('color', 'red');
});

The jQuery syntax is tailor made for selecting HTML elements and perform some action on the element(s).

Basic syntax is: $(selector).action()

A dollar sign to define jQuery A (selector) to "query (or find)" HTML elements A jQuery action() to be performed on the element(s)

More on this

Additional to the jQuery thing treated in the other answers there is another meaning in JavaScript - as prefix for the RegExp properties representing matches, for example:

"test".match( /t(e)st/ );
alert( RegExp.$1 );

will alert "e"

But also here it's not "magic" but simply part of the properties name

In jQuery, the $ sign is just an alias to jQuery(), then an alias for a function.

This page reports:

Basic syntax is: $(selector).action()

  • A dollar sign to define jQuery
  • A (selector) to "query (or find)" HTML elements
  • A jQuery action() to be performed on the element(s)