2013-07-25 13 views
0

我有兩個網頁。他們共享相同的.js文件,但該文件包含我只想執行其中一個或另一個頁面的代碼。在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(); 
+0

爲兩個不同的網頁混合了js代碼?我不認爲這是一個好主意。 –

+0

這很常見。它們是同一站點內的頁面,它減少了加載scipt的調用次數。 – user984003

+0

讓你的後端代碼根據它呈現的視圖來決定將要加載哪些js文件,這將減少你需要加載的整個JS。 –

回答

0

就像我在我的評論說,我不認爲這是一個好主意,但我仍然會爲您提供一種方法來解決你的問題:使用closures

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(); 
+0

這工作,謝謝。我還添加了一個基於你的答案,這說明我是如何最終做到的。 – user984003

3

在JavaScript中,函數聲明是hoisted。您的代碼變成:

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

0

基於曼努埃爾Görlich的回答,H我的結局是如何做到的。我將每個代碼集封裝在一個閉包中,然後我將所有其他東西保持原樣。對runStartFunction()的調用必須位於每個閉包中。

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(); 

}());} 
相關問題