Javascript Drupal 7 jQuery函数调用问题
我在Drupal中遇到了以下问题,但这可能不完全是Drupal特有的问题 我有以下简单的javascript:Javascript Drupal 7 jQuery函数调用问题,javascript,jquery,drupal-7,Javascript,Jquery,Drupal 7,我在Drupal中遇到了以下问题,但这可能不完全是Drupal特有的问题 我有以下简单的javascript: (function ($) { function testing(){ alert('TEST function responding!'); } })(jQuery); 我正试图使用以下代码从Drupal模块调用该函数: drupal_add_js('jQuery(document).ready(function () { testing(); });',
(function ($) {
function testing(){
alert('TEST function responding!');
}
})(jQuery);
我正试图使用以下代码从Drupal模块调用该函数:
drupal_add_js('jQuery(document).ready(function () { testing(); });',
array('type' => 'inline', 'scope' => 'footer', 'weight' => 5)
);
但是,我得到一个错误,它是uncaughtreferenceerror:testing未定义
我想利用jQuery在该函数中的功能,这就是我不使用普通JavaScript文件的原因。快速而肮脏的回答:定义
testing()
的范围和调用它的范围不同。您可以定义测试全局范围,然后它就可以工作了,尽管这不是大型应用程序的最佳实践
(function ($) {
window.testing = function(){
alert('TEST function responding!');
}
})(jQuery);
如果要将函数扩展到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)
);
您是否将代码的第一部分存储在外部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)
);