Using JQuery in Drupal 7

前端 未结 5 617
长情又很酷
长情又很酷 2021-01-30 17:18

I\'m writing my own Drupal 7 module, and like to use JQuery in it.

$(\'#field\').toggle();

But I\'m getting this error:

TypeErr         


        
相关标签:
5条回答
  • 2021-01-30 17:37

    According to Firebug, your jQuery file is being loaded:

    alt text

    But the $ is being overwritten by something else:

    alt text


    What you should do is encapsulate the use of the $ variable with a function that invokes itself using the jQuery object as it's first actual argument:

    (function ($) {
    
     // in this function, you can use the $ which refers to the jQuery object
    
    }(jQuery));
    
    0 讨论(0)
  • 2021-01-30 17:49

    You can create the separate file for js and than add js file using the following:

    drupal_add_js('path', 'module_name');
    
    0 讨论(0)
  • 2021-01-30 17:51

    "$ is not a function" is a very common error that you may face while working with jQuery. You can try any answers of given below:

    (function($){
    //your can write your code here with $ prefix
    })(jQuery);
    

    OR

    jQuery(document).ready(function($){
    //Write your code here
    });
    

    Basically this will allow our code to run and use the $ shortcut for JQuery.

    0 讨论(0)
  • 2021-01-30 17:57

    Chances are your script is not initialized this way, you'll have to use Drupal.behaviors.YOURTHEMENAME

    (function ($) {
    Drupal.behaviors.YOURTHEMENAME = {
    attach: function(context, settings) {
    
    /*Add your js code here*/
    alert('Code');
    
    }
    
    };
    })(jQuery);    
    
    0 讨论(0)
  • 2021-01-30 18:04

    From the Drupal 7 upgrade guide:

    Javascript should be made compatible with other libraries than jQuery by adding a small wrapper around your existing code:

    (function ($) {
      // Original JavaScript code.
    })(jQuery);
    

    The $ global will no longer refer to the jquery object. However, with this construction, the local variable $ will refer to jquery, allowing your code to access jQuery through $ anyway, while the code will not conflict with other libraries that use the $ global.

    You can also just use the 'jQuery' variable instead of the $ variable in your code.

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