我正在编写自己的Drupal 7模块,并且喜欢在其中使用jQuery。

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

但是我遇到了这个错误:

TypeError: Property '$' of object [object DOMWindow] is not a function

似乎没有加载jQuery。否则应定义$。

尽管我实际上将其包括在标题中:

<script type="text/javascript" src="http://rockfinder.de/misc/jquery.js?v=1.4.4"></script>

我是否必须做其他事情来激活Drupal? $是被Drupal覆盖的吗?

那是网站: http://rockfinder.orgapage.de

有帮助吗?

解决方案

来自Drupal 7升级指南:

JavaScript应与JQuery以外的其他库兼容,通过在您现有代码周围添加一个小包装:

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

$ Global将不再是指jQuery对象。但是,使用此构造,本地变量$将指jQuery,允许您的代码通过$访问jQuery,而代码不会与使用$ Global的其他库发生冲突。

您也可以只使用代码中的“ jQuery”变量而不是$变量。

其他提示

根据Firebug的说法,您的jQuery文件正在加载:

alt text

但是 $ 被其他事物覆盖:

alt text


您应该做的是封装 $ 可变量,可以使用该函数来调用自身 jQuery 对象是第一个实际参数:

(function ($) {

 // in this function, you can use the $ which refers to the jQuery object

}(jQuery));

机会是您的脚本不是这样初始化的,您必须使用drupal.behaviors.yourthemename

(function ($) {
Drupal.behaviors.YOURTHEMENAME = {
attach: function(context, settings) {

/*Add your js code here*/
alert('Code');

}

};
})(jQuery);    

您可以为JS创建单独的文件,并使用以下内容添加JS文件:

drupal_add_js('path', 'module_name');

“ $不是函数”是您在使用jQuery时可能会遇到的一个非常常见的错误。您可以尝试以下给出的任何答案:

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

或者

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

基本上,这将允许我们的代码运行并使用$快捷方式用于jQuery。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top