大家好,我有这个问题只是在烦扰我,我无法理解。我到处寻找,无法找到答案。
我有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>
这是我的第二个html文件,链接到相同的外部javsascript文件
<!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文件?
答案 0 :(得分:2)
在第一个 HTML页面中,button1
是一个按钮,button2
是null
。
button1.addEventListener("click", sayHello, false);
绑定事件处理程序,然后button2.addEventListener("click", sayHello, false);
错误。由于函数中没有更多代码,除非您正在观看JS控制台,否则这没有明显的效果。
在第二个 HTML页面中,情况恰恰相反:button2
是一个按钮,button1
是null
。
button1.addEventListener("click", sayHello, false);
错误,它永远不会到达下一行。
在绑定之前测试if (button1) {}
和if (button2) {}
...并在遇到问题时查看JavaScript错误控制台。