我的jQuery函数的范围?

时间:2011-11-21 15:50:06

标签: javascript jquery scope

我有一个名为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();,它在初始加载时运行....这很有效。我的问题是我现在需要将这个js文件包含在我的php页面说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
});

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

4 个答案:

答案 0 :(得分:1)

尝试命名空间函数并将它们附加到一个漂亮的全局对象。

window.MyApp = {};

MyApp.insert_initial = function(){

};

然后您可以从您需要的任何地方访问它,只要它包含在页面前面。

编辑:

如果这不起作用,您的代码中的其他地方会出现错误 - 也许是加载顺序?你所描述的调用函数的方法都很好,只需确保在调用它时定义它。

答案 1 :(得分:1)

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

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

答案 2 :(得分:1)

我建议在这种情况下将您的定义和执行分开。您不需要在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>

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

答案 3 :(得分:0)

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