What is the difference between $ and jQuery

后端 未结 6 1515
自闭症患者
自闭症患者 2020-12-02 01:31

When I try to use $(\"#div_id\") in $(document).ready it returns NULL, but when I use jQuery(\"#div_id\") it returns the actual object

相关标签:
6条回答
  • 2020-12-02 02:03

    $ is also used in Prototype.js, which is a javascript framework like jQuery. It could be the case that your project also includes references to this framework.

    For more info on how the prototype dollar works, go here.

    You can make the two work together with the noConflict statement, as stated in the other answers. We're doing this in one of our projects, which uses the $(element) for legacy prototype code, and jQuery(element) for new jQuery code.

    0 讨论(0)
  • 2020-12-02 02:13

    See jQuery.noConflict(). Could other javascript libraries on your page be using the $ variable?

    $ is just a variable that is used to alias jQuery and being a variable, anything could be assigned to it.

    0 讨论(0)
  • 2020-12-02 02:13

    jQuery and $ are the same - see jQuery source code:

    window.jQuery = window.$ = jQuery;
    

    Maybe you use another library that uses variable $ and then you have to solve naming conflict.

    <script type="text/javascript">
      jQuery.noConflict();
      jQuery(document).ready(function($) {
        // Code that uses jQuery's $ can follow here.
      });
      // Code that uses other library's $ can follow here.
    </script>
    

    Or you can use one of the following snippet (in it's body there will be no conflict of $):

    // Method 1
    jQuery(document).ready(function($){
        /* some code that uses jQuery $ */ 
    });
    
    // Method 2
    (function($) {
        /* some code that uses jQuery $ */ 
    })(jQuery);
    
    0 讨论(0)
  • 2020-12-02 02:15

    $ and jQuery both are same except $ is just an alias of jQuery which you can change or remove with jQuery.noConflict mode.

    0 讨论(0)
  • 2020-12-02 02:17

    Maybe you have another library that uses $?

    0 讨论(0)
  • 2020-12-02 02:19

    Looks like something has taken the $, to reassign jQuery to $, try going:

    var $ = jQuery;
    
    0 讨论(0)
提交回复
热议问题