2014-03-25 14 views
1

大家好我有這個問題,只是糾纏我,我不能弄明白。我無處不在,無法找到答案。相同的window.addEventListener對於2個html文件

我有2個HTML文件和1個外部JavaScript文件....

這是第一個HTML文件

<!doctype html> 

<head> 
    <title>.....</title> 
    <script src="externalJsFile"></script> 
</head> 

<body> 
    <input type="button" value="button1" id="button1"> 
    </div> 
</body> 

<html> 

這裏是我的鏈接到同一個外部javsascript文件

第二HTML文件
<!doctype html> 

<head> 
    <title>.....</title> 
    <script src="externalJsFile"></script> 
</head> 

<body> 
    <input type="button" value="button2" id="button2"> 
    </div> 
</body> 
</html> 

這裏是我的外部JavaScript文件

window.addEventListener("load", setFunctions, false); 


function setFunctions() { 
    var button1 = document.getElementById("button1"); 
    var button2 = document.getElementById("button2"); 

    button1.addEventListener("click", sayHello, false); 
    button2.addEventListener("click", sayHello, false); 
} 


function sayHello() { 
    alert("hello"); 
} 

當我訪問每個html頁面以單擊按鈕以查看hello彈出框時,它只能在其中一個頁面中工作。在JavaScript中,如果我切換按鈕上的事件偵聽器的順序,那麼彈出窗口現在只能在其他頁面上工作!有人請幫助!當使用窗口事件偵聽器時,是否需要爲每個html頁面單獨使用外部JavaScript文件?

+2

爲什麼用'jQuery'標記? –

+0

我沒有注意到任何開始''標記.... –

+0

@GaurangTandon - HTML元素的開始標記被定義爲可選。 – Quentin

回答

2

第一 HTML頁面,button1是一個按鈕,button2null

button1.addEventListener("click", sayHello, false);綁定事件處理程序,然後button2.addEventListener("click", sayHello, false);錯誤。由於函數中沒有更多的代碼,除非您正在觀看JS控制檯,否則這沒有明顯的影響。

HTML頁面,它是周圍的其他方式:button2是一個按鈕,button1null

button1.addEventListener("click", sayHello, false);錯誤,它永遠不會到達下一行。

測試,看看if (button1) {}if (button2) {}綁定之前...看看你的JavaScript錯誤控制檯,當你有問題。

+0

非常感謝你!我添加了if語句並修復了它。謝謝! –

相關問題