【问题标题】:Custom module: Uncaught TypeError: undefined is not a function自定义模块:未捕获类型错误:未定义不是函数
【发布时间】:2015-02-25 03:25:33
【问题描述】:

我正在尝试编写自己的 Drupal 模块,并且我想要包含 Javascript。我尝试包含一个非常简单的 jquery 文件,但我不断收到 Uncaught 'TypeError: undefined is not a function'。 我已经更新了 Drupal 的 jQuery 版本。

作为参考,这些是我正在使用的脚本。

我的 .info 文件

name = Test
description = A slideshow that implements the PgwSlider Javascript.
core = 7.x

我的 .module 文件

 /**
 * Implements hook_help().
 *
 * Displays help and module information.
 *
 * @param path 
 *   Which path of the site we're using to display help
 * @param arg 
 *   Array that holds the current path as returned from arg() function
 */
function test_help($path, $arg) {
  switch ($path) {
    case "admin/help#pgwslider":
      return '<p>' . t("Displays a slideshow") . '</p>';
      break;
  }
}

function test_init() {
    drupal_add_css(drupal_get_path('module', 'test') .'/styles.css');
    drupal_add_js(drupal_get_path('module', 'test') .'/test.js');
}

我的 .js 文件

$(document).ready(function() {
    $('p').click(function(){
        $(this).hide();
    });
    console.log('test')
});

有什么想法吗?

第二个小问题:

这是包含 js 文件的最佳方式吗?我知道在主题中这是在 .info 文件中完成的,但是对于模块,我没有找到全面的答案。

谢谢大家!

【问题讨论】:

    标签: javascript jquery drupal module drupal-7


    【解决方案1】:

    假设你的.js文件的路径是正确的,你必须阅读一些standards of JavaScript code

    你所有的 JS 代码必须像下面这样声明:

    /**
     * @file
    */
    (function ($) {
      "use strict";
    
      // Your js code
    
    })(jQuery);
    

    你添加JS的方式已经足够好了,但我建议你使用hook_library()

    【讨论】:

    • 或者使用jQuery 代替$ 符号。 jQuery(this).hide(); 应该可以正常工作。
    • 我确定我的路径是正确的,因为在检查资源时我可以看到加载的 test.js 文件。这就是我现在所拥有的,但我仍然遇到同样的错误。我已经阅读了 Drupal 文档,但是唉。 /** * @file */ (function () { "use strict"; $(document).ready(function () { $('p').click(function () { $(this).hide(); }); console.log('test'); }); })(jQuery); 编辑:Pastebin 用于清洁代码 pastebin.com/Gczd0m3T
    • 没关系,让它工作。我从 drupal 文档中复制了代码,该文档在封闭函数的参数中没有 $ 符号。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2015-03-14
    • 2014-08-11
    • 2015-04-14
    • 2014-12-13
    • 1970-01-01
    相关资源
    最近更新 更多