我有一个index.html文件:
<head>
<title>Jiggle Into JavaScript</title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<p>Press the buttons to change the box!</p>
<div id="box" style="height:150px; width:150px; background-color:darkorange; margin:25px"></div>
<button type="button1" onclick="growFunc()">Grow</button>
<button type="button2" onclick="blueFunc()">Blue</button>
<button type="button3" onclick="fadeFunc()">Fade</button>
<button type="button4" onclick="resetFunc()">Reset</button>
<script type="text/javascript" src="javascript.js"></script>
</body>
我的 javascript.js 文件如下所示:
function growFunc() {
document.getElementById("button1").addEventListener("click",
function(){document.getElementById("box").style.height = "250px";
});
}
function blueFunc() {
document.getElementById("button2").addEventListener("click",
function(){document.getElementById("box").style.backgroundColor = "blue";
});
}
function fadeFunc() {
document.getElementById("button3").addEventListener("click", function(){
document.getElementById("box").style.backgroundColor = "orange";
});
}
function resetFunc() {
document.getElementById("button4").addEventListener("click",
function(){
document.getElementById("box").style.height = "150px";
document.getElementById("box").style.backgroundColor = "darkorange";
});
}
两个文件位于同一目录中。例如,当我尝试在 Firefox 中运行 index.html 时,单击按钮时没有任何反应。但如果我的功能都在index.html 文件中(见下文),它就可以工作。我似乎找不到我的代码有什么问题(我是新手)。感谢您的帮助。
<head>
<title>Jiggle Into JavaScript</title>
<p>Press the buttons to move the box!</p>
<div id="box" style="height:150px; width:150px; background-color:darkorange; margin:25px"></div>
<button id="growBtn">Grow</button>
<button id="blueBtn">Blue</button>
<button id="fadeBtn">Fade</button>
<button id="resetBtn">Reset</button>
<script type="text/javascript">
document.getElementById("growBtn").addEventListener("click", function(){
document.getElementById("box").style.height = "250px";
});
document.getElementById("blueBtn").addEventListener("click", function(){
document.getElementById("box").style.backgroundColor = "blue";
});
document.getElementById("fadeBtn").addEventListener("click", function(){
document.getElementById("box").style.backgroundColor = "orange";
});
document.getElementById("resetBtn").addEventListener("click", function()
document.getElementById("box").style.height = "150px";
document.getElementById("box").style.backgroundColor = "darkorange";
});
</script>
</body>
最佳答案
您正在内联点击处理程序中绑定(bind)事件处理程序,因此当您点击一次时它不会产生任何效果。
在您的 javascript 文件中使用 DOMContentLoaded
等待 DOM 完全加载然后绑定(bind)事件处理程序的事件
document.addEventListener("DOMContentLoaded", function(event) {
//Bind event handlers
document.getElementById("button1").addEventListener("click", function(){
.....
});
});
并摆脱丑陋的内联事件处理程序。
关于javascript - 无法从 html 文件使用的外部 javascript 文件读取函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44947578/