[英]Drupal 7 jQuery function call issue
我在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:未定义测试
我想利用该函数中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)
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.