0

我有两个网页。它们共享相同的 .js 文件,但该文件包含我只想为其中一个或另一个页面执行的代码。

我想我可以像下面这样处理它,每个页面都有一个具有唯一 id 的元素,“page_1”或“page_2”。然后 js 在执行代码之前测试这个元素的存在。

然而,在 page_1 上,即使它实际上并没有执行 page_2 IF 语句中的代码,函数 runStartFunction() 仍然被覆盖,因为它被定义了两次。

我怎样才能避免这种情况?显然我可以给所有的函数起不同的名字,但是我有很多页面,有时我可能会不小心使用相同的名字。

if (document.getElementById("page_1") != null){
    alert("Page 1"); // executed, as expected
    function runStartFunction(){
        alert("what I want"); // not executed, but should be
    }
}

 if (document.getElementById("page_2") != null){
   alert("Page 2"); // not executed, as expected
   function runStartFunction(){ 
        alert("what I don't want"); // executed, but shouldn't be
   }
 }

runStartFunction();
4

3 回答 3

3

在 JavaScript 中,函数声明是提升的。您的代码变为:

function runStartFunction() {
    alert("what I want");
}

function runStartFunction() { 
    alert("what I don't want");
}

if (document.getElementById("page_1") != null) {
    alert("Page 1");
}

if (document.getElementById("page_2") != null) {
    alert("Page 2");
}

runStartFunction();

第二个声明runStartFunction覆盖了第一个,所以调用了第二个。

您可以使用函数表达式和赋值而不是声明来解决这个问题,如下所示:

var runStartFunction;

if (document.getElementById("page_1") != null) {
    alert("Page 1");
    runStartFunction = function () {
        alert("what I want");
    };
}

if (document.getElementById("page_2") != null) {
    alert("Page 2");
    runStartFunction = function () { 
        alert("what I don't want");
    };
}

runStartFunction();

小提琴:http: //jsfiddle.net/nYPME

于 2013-07-25T05:41:32.763 回答
0

Based on Manuel Görlich's answer, here is how I ended up doing it. I surround each code set in a closure and then I just leave everything else as it was. The call to runStartFunction() has to be inside each closure.

if (document.getElementById("page_1") != null){(function () { 

   alert("Page 1");
   function runStartFunction(){
        alert("what I want");
    }
    runStartFunction();

}());}

if (document.getElementById("page_2") != null){(function () { 


    alert("Page 2");
    function runStartFunction(){ 
        alert("what I don't want");
     }
    runStartFunction(); 

}());}
于 2013-07-25T06:22:30.513 回答
0

就像我在评论中所说的那样,我认为这不是一个好主意,但我仍然会为您提供解决问题的方法:使用闭包

var runStartFunction;
if (document.getElementById("page_1") != null){
    (function () { 
        alert("Page 1"); // executed, as expected
        runStartFunction = function startFunction(){
            alert("what I want"); // not executed, but should be
        }
    }());
}

if (document.getElementById("page_2") != null){
    (function () { 
        alert("Page 2"); // not executed, as expected
        runStartFunction = function startFunction(){ 
            alert("what I don't want"); // executed, but shouldn't be
        }
    }());
}

runStartFunction();
于 2013-07-25T05:45:59.463 回答