$ 不是 Drupal 上的函数错误

$ is not a function error on Drupal

我的代码在本地环境下运行良好,但在网站上运行不正常。我不明白我在这里错过了什么。

代码:

jQuery(document).ready(function(){
  'use strict';
  //============================== COUNTER-UP =========================
  $('.counter').counterUp({
    delay: 10,
    time: 2000
  });
});

错误信息:

Uncaught TypeError: $ is not a function
    at HTMLDocument.<anonymous> (custom.js?p4xosk:4)
    at fire (jquery.js?v=1.10.2:3048)
    at Object.fireWith [as resolveWith] (jquery.js?v=1.10.2:3160)
    at Function.ready (jquery.js?v=1.10.2:433)
    at HTMLDocument.completed (jquery.js?v=1.10.2:104)

在 Drupal 中 $ 不默认为 jQuery。 作为最佳实践,您也不应该自己分配它。 只需在您的代码中使用 "jQuery" 而不是“$”,例如将 $('.counter') 替换为 jQuery('.counter')

你必须定义 $ :

(function($){
 $(document).ready(function(){
  'use strict';
  //============================== COUNTER-UP =========================
  $('.counter').counterUp({
    delay: 10,
    time: 2000
  });
 });
})(jQuery);