在Drupal 7中使用JQuery

问题描述 投票:32回答:5

我正在编写自己的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中激活JQuery?是否被Drupal覆盖?

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

javascript jquery drupal drupal-7
5个回答
89
投票

From the Drupal 7 upgrade guide:

通过在现有代码周围添加一个小包装器,Javascript应该与jQuery之外的其他库兼容:

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

$ global将不再引用jquery对象。但是,使用这种结构,局部变量$将引用jquery,允许您的代码通过$访问jQuery,而代码不会与使用$ global的其他库冲突。

您也可以在代码中使用'jQuery'变量而不是$ variable。


14
投票

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

$被其他东西覆盖:


你应该做的是使用$对象封装jQuery变量的使用,该函数使用(function ($) { // in this function, you can use the $ which refers to the jQuery object }(jQuery)); 对象作为它的第一个实际参数:

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

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

}

};
})(jQuery);    

8
投票

有可能你的脚本没有这样初始化,你必须使用Drupal.behaviors.YOURTHEMENAME

drupal_add_js('path', 'module_name');

1
投票

您可以为js创建单独的文件,然后使用以下命令添加js文件:

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

0
投票

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

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

要么

qazxswpoi

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

© www.soinside.com 2019 - 2024. All rights reserved.