简体   繁体   中英

What is the difference between a dollar sign and a dollar sign followed by a period in JQuery?

In jQuery, what is the difference between $ and $. ? Please provide a practical explanation if possible.

$ is a reference (or synonym, if you want an analogy) to the global jQuery object. $.<method> calls a static method of the jQuery object, where $(<selector>) creates a new instance of the jQuery object.

In the context of jQuery, $ refers to the global jQuery object .

$. by itself is invalid JavaScript. As $ is an object , methods on this object are called like on any other object: $.methodname() .

Maybe it becomes clearer by substituting $ with jQuery : jQuery.methodname() .

I presume you are asking about the syntactic difference between $('#selector'); and $.parseJSON(str); .

The former is an invocation of a function called $ and the latter invokes it's method called parseJSON . Yup, functions can have methods - it is possible because Javascript functions are also objects. Figuratively speaking:

<script type="text/javascript">

function $(str) {
   alert(str);
}

$.parseJSON = function () {
   alert('Parsing JSON');
}

$('Hi');
$.parseJSON('{}');


</script>

$ - dollar sign is also same as Jquery usage. But I preferred to use dollar sign because I like the way dollar sign is.

From http://en.wikipedia.org/wiki/JQuery :

the $ function, which is a factory method for the jQuery object. These functions, often called commands, are chainable; they each return a jQuery object

$.-prefixed functions. These are utility functions which do not work on the jQuery object per se.

Typically, access to and manipulation of multiple DOM nodes begins with the $ function being called with a CSS selector string, which results in a jQuery object referencing matching elements in the HTML page. This node set can be manipulated by calling instance methods on the jQuery object, or on the nodes themselves. For example:

 $("div.test").add("p.quote").addClass("blue").slideDown("slow"); 

This line finds the union of all div tags with class attribute test and all p tags with CSS class attribute quote, adds the class attribute blue to each matched element, and then slides them down with an animation. The $ and add functions affect the matched set, while the addClass and slideDown affect the referenced nodes.

The methods prefixed with $. are convenience methods or affect global properties and behaviour. For example, the following is an example of the map function called each in jQuery:

 $.each([1,2,3], function(){ document.write(this + 1); }); 

This writes the number 234 to the document.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM