开发者

What does JS $ mean?

I don't grok the idea/purpose/u开发者_开发技巧se of Javascript $, as in

function $(id) { return document.getElementById(id); }

Could someone please explain or point me at an explanation?

Thanks!

-- Pete


When you see JavaScript code that involves lots of $(foo) function calls, it's probably using either the jQuery or the Prototype web development frameworks. It's just an identifier; unlike a lot of other languages, identifiers (function and variable names) can include and start with "$".


In your code it is the name of a function.

function $(id) { return document.getElementById(id); }
$("my_id")

function myfunc(id) { return document.getElementById(id); }
myfunc("my_id")

Two functions, two different identifiers.


Most commonly this is used by JQuery - specifically, JQuery creates an object with a reference of $ which has various methods to simplify page manipulation.

It's technically possible for anything to attach a class to $


It's just the name of a function called $(). The dollar sign ($) is a valid character for identifiers in JavaScript. jQuery, for example, uses it as a shorthand alias for the jQuery() function.


There are two main reasons to use $ as a function name, especially in frameworks like jQuery:

  • It's short but distinctive - you're going to use it all over the place, so you don't want it to take up too much space.
  • When used as a DOM element selector, the function and its parameters together kind of look like a Perl/PHP/Java properties variable - and it kind of works like that as well, since the main purpose is to do something with the selected DOM elements.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜