繁体   English   中英

我的jQuery函数的范围?

[英]Scope of my jQuery function?

我有一个名为function.js的文件,其中包含我所有的jQuery应用程序,看起来像这样

$(document).ready(function(){

    insert_initial(); //first time to the page, insert into cart and set the subtotal originally

    function update_gallery(product_id){
        ...
    }

    function update_prices(product_selector){
        ...
        ...
    }

    function insert_initial(){
        ...
    }

    $('.trigger').click(function(){
        $('.stations').find(".drop-down").slideToggle();
        return false;
    });

    ...
    ...

在文件的顶部,我有一个函数调用insert_initial(); 我的问题是我现在需要在我的php页面上包含此js文件,说1.php和2.php以及3.php和1.php是。唯一需要insert_initial(); ....所以我在想最好的方法。 我假设从函数文件中取出函数调用,并将其放入单独的文件中

<script src="/someting/js/functions.js" type="text/javascript"></script>
<script src="/someting/js/functions_insert.js" type="text/javascript"></script> 

在我的functions_insert.js文件中,我只有

$(document).ready(function(){
insert_initial(); //first time to the page, insert into cart and set the subtotal originally
});

但这还是没有用...关于如何解决这个问题的任何想法

尝试为函数命名,并将它们附加到一个不错的全局对象上。

window.MyApp = {};

MyApp.insert_initial = function(){

};

然后,您可以从任何需要的位置访问它,前提是该页面前面包含了该信息。

编辑:

如果这不起作用,则您的代码中的其他地方有错误-可能是加载顺序? 您描述的两种方法都可以调用该函数,只要确保在调用该函数时已定义该方法即可。

这将在调用insert_initial()之前检查以确保当前页面的位置包括“ 1.php”:

if(window.location.href.indexOf('1.php') != -1)
    insert_initial();

我建议在这种情况下将您的定义和执行分开。 您无需在jQuery的DOM ready事件中定义函数。 但是也可以像上面提到的那样对它们进行命名空间。 我遵循的常见范例如下:

functions.js

(function($, window, undefined) {
    function update_gallery(product_id){
        ...
    }

    function update_prices(product_selector){
        ...
        ...
    }

    function insert_initial(){
        ...
    }

    window.MyApp = {
        update_gallery: update_gallery,
        update_prices: update_prices,
        insert_initial: insert_initial
    };
})(jQuery, window); 

1.php

<script src="functions.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
    MyApp.insert_initial();
});
</script>

现在,您可以根据需要包括您的定义,并根据需要调用它们。

functions.js中定义的functions.js仅在该文档就绪函数的范围内可见。 一个不起作用的简单情况:

(function() {
    function square(x) {
        return x*x;
    }
})();

alert(square(2)); //Fails, since square is not in scope

解决此问题的最简单方法是在全局名称空间中声明函数:

function square(x) {
    return x*x;
};

alert(square(2)); //4

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM