【问题标题】:Drupal 7 jQuery function call issueDrupal 7 jQuery 函数调用问题
【发布时间】:2012-10-17 14:30:33
【问题描述】:

我在 Drupal 中遇到以下问题,但这可能不完全是 Drupal 特有的问题。

我有以下简单的javascript:

(function ($) {

  function testing(){
    alert('TEST function responding!');
  }

})(jQuery);

我正在尝试使用以下代码从我的 Drupal 模块调用该函数:

drupal_add_js('jQuery(document).ready(function () { testing(); });',
  array('type' => 'inline', 'scope' => 'footer', 'weight' => 5)
);

但是,我收到一条错误消息 Uncaught ReferenceError: testing is not defined

我想在该函数中利用 jQuery 的能力,这就是我不使用普通 JavaScript 文件的原因。

【问题讨论】:

    标签: javascript jquery drupal-7


    【解决方案1】:

    快速而肮脏的答案:您定义testing() 的范围与您调用它的范围不同。您可以定义测试全局范围,然后它会起作用,尽管这不是大型应用程序的最佳实践。

    (function ($) {
        window.testing = function(){
            alert('TEST function responding!');
        }
    })(jQuery);
    

    【讨论】:

      【解决方案2】:

      如果你想将你的函数扩展到 jQuery 变量,你可以这样做:

      if( !jQuery.testing ){
      
      jQuery.extend( {
          testing: function() { 
              console.log("Calling from extend function in jQuery");
          }
      });
      }
      

      并称它为:

      drupal_add_js('jQuery(document).ready(function () { jQuery.testing(); });',
        array('type' => 'inline', 'scope' => 'footer', 'weight' => 5)
      );
      

      【讨论】:

        【解决方案3】:

        您是否将代码的第一部分存储在外部 JavaScript 中?使用 drupal_add_js 来引用它,例如,

        drupal_add_js('js/external.js');
        
        //external.js
        jQuery.noConflict();
        jQuery(document).ready(function($) {
        window.testing = function(){
            alert('TEST function responding!');
        // The useful part of this is the ability to use $ from now on. e.g., $('body').hide();
        }
        });
        });
        

        然后添加你的 JavaScript

        drupal_add_js('jQuery(document).ready(function () { testing(); });',
        array('type' => 'inline', 'scope' => 'footer', 'weight' => 5)
        );
        

        【讨论】:

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