【问题标题】:Add JS file on a certain page on Drupal在 Drupal 的某个页面上添加 JS 文件
【发布时间】:2010-06-18 00:21:55
【问题描述】:

我有一个 JS 文件要添加到管理员>添加内容>某些内容类型
查看 template.php 并查看函数 theme_preprocess_node
我试图通过 drupal_add_js(...) 添加 JS 但不行。
现在,我知道有一个类似的问题,但是我的情况是关于添加
一个 JS 文件到某个页面,仅此而已(更好地分离 JS 文件)。

谢谢。
(Drupal 6)

【问题讨论】:

    标签: drupal drupal-6 javascript


    【解决方案1】:

    查看drupal_add_js() in page template not working

    它的要点是在预处理函数期间调用drupal_add_js()(或drupal_add_css())基本上为时已晚,因为 js/css 包含的标记已经呈现为变量。要解决此问题,您需要在添加后通过调用 drupal_get_js() 再次覆盖该变量:

    function yourThemeName_preprocess_page(&$variables) {
      // Is this a node addition page for the specific content type?
      // TODO: Adjust the content type to your needs
      // NOTE: Will only work for the node add form - if you want your js to be
      // included for edit forms as well, you need to enhance the check accordingly
      if ('node' == arg(0) && 'add' == arg(1) && 'yourContentType' == arg(2)) {
        // Add your js file as usual
        drupal_add_js('path/to/your/file.js', 'theme');
        // Ensure that the addition has any effect by repopulating the scripts variable
        $variables['scripts'] = drupal_get_js();
      }
    }
    

    注意:请使用preprocess_page,而不是preprocess_node,因为页面模板中应该包含javascript。此外,Kevins 暗示需要重建主题注册表仍然适用 (+1)。

    【讨论】:

    • 这是正确的!我还在这里解释了如何在主题级别添加自定义 js:stackoverflow.com/questions/3051765/…
    • 好吧,但是看起来这个 JS 文件会被加载到每个页面上,而我希望它被加载到某个页面上(否则会浪费加载时间)
    • @ASAF:您似乎错过了示例中的“TODO”注释;)
    • @ASAF:好的,我刚刚添加了页面检查逻辑。
    【解决方案2】:

    在你的模块中你可以做一个:

    function your_module_name_init() {
        if(arg(0) == "some_name") {
            drupal_add_js(drupal_get_path('module', 'your_module_name') . '/your_js_file_name.js');
        }
    }
    

    类似的东西?

    【讨论】:

      【解决方案3】:

      添加 drupal_add_js 后,您是否清除了主题/站点缓存?应该可以的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-03
        • 1970-01-01
        相关资源
        最近更新 更多