调用位于单独文件中的jQuery函数

时间:2012-07-13 08:14:54

标签: jquery file external

我的脚本变得越来越难以维护,我想将其中一部分移动到一个单独的文件中,但无法使其工作。

我有以下内容:

jQuery(document).ready(function ($) {

some code....

initEdit(theme, isAdmin, dataAdapterCustomers, dataAdapterShops, dataAdapterOrderStatus);

some more code.....

});

在edit.js文件中,我有以下内容:

function initEdit(theme, isAdmin, dataAdapterCustomers, dataAdapterShops, dataAdapterOrderStatus) {

        $("#dateEdit").jqxDateTimeInput({ 
            width: '200px', 
            height: '18px', 
            formatString: "yyyy-MM-dd",
            theme: theme  
        });

some more code.....

}

执行此操作时,我收到以下错误:

  

未捕获的TypeError:对象[对象DOMWindow]的属性'$'不是函数

我尝试用以下内容包含initEdit函数:

(function($) {
function initEdit(theme, isAdmin, dataAdapterCustomers, dataAdapterShops, dataAdapterOrderStatus) {

        $("#dateEdit").jqxDateTimeInput({ 
            width: '200px', 
            height: '18px', 
            formatString: "yyyy-MM-dd",
            theme: theme  
        });

some more code.....

}})(jQuery);

然后我收到一个错误,它无法找到initEdit。

我确实包含了额外的.js文件,当我检查文件的源代码并单击它时,它会加载,因此页面会加载它。我必须补充一点,原始的jQuery脚本是在php文件中的脚本标记内。我还在noConflict模式下运行jQuery。

是否可以在从主函数调用edit.js之前执行它?

任何建议都将受到高度赞赏!

3 个答案:

答案 0 :(得分:0)

试试这个:

function initEdit(theme, isAdmin, dataAdapterCustomers, dataAdapterShops, dataAdapterOrderStatus) {

        jQuery("#dateEdit").jqxDateTimeInput({ 
            width: '200px', 
            height: '18px', 
            formatString: "yyyy-MM-dd",
            theme: theme  
        });
}

答案 1 :(得分:0)

是否有包含.js文件的正确顺序? 确保首先加载主jqueryfile,然后是edit.js,然后是调用该函数的代码。错误看起来不知道jquery-syntax。

答案 2 :(得分:0)

同意@ 32bitfloat,您必须拥有包含.js文件的正确顺序..

第一次包含jquery文件 <script type="text/javascript" src="jquery.js">

然后包含你的文件包含的功能 <script type="text/javascript" src="function.js">

然后致电

(function ($){ code here... })