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

前端 未结 5 1582
余生分开走
余生分开走 2021-01-12 10:48

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

相关标签:
5条回答
  • 2021-01-12 11:12

    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>
    
    0 讨论(0)
  • 2021-01-12 11:13

    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.

    0 讨论(0)
  • 2021-01-12 11:14

    $ 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.

    0 讨论(0)
  • 2021-01-12 11:18

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

    0 讨论(0)
  • 2021-01-12 11:23

    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().

    0 讨论(0)
提交回复
热议问题