我想知道如果有人能为我提供一个教学点。我正在尝试学习Javascript,并且此代码的逻辑对我来说似乎合理,但由于某种原因它不起作用。为什么这个简单的事件监听器不能在Javascript中工作?
它基本上是一个按钮。我试图做到这一点,当按钮被点击时,变量testingVar变为我的switch语句的条件之一。然而,当我点击按钮时,没有发生警报。
有人可以请解释为什么当我点击按钮时没有任何提示,我会如何使它工作?
<html>
<body>
<a id="myButton" href="#">CLICK</a>
<script>
var myButton = document.getElementById("myButton");
var testingVar;
myButton.addEventListener("click", function() {
testingVar = "hello";
}, false);
switch (testingVar) {
case "hello" :
alert("You've got the hello condition!");
break;
case "goodbye" :
alert("You've got the goodbye condition");
break;
} // end switch statement
</script>
</body>
</html>
谢谢。
当您点击链接时,'testsVar'将成为'“hello”'。当'testingVar'为空时页面加载后,您的switch语句就立即执行 – Satpal
交换机仅在第一个页面加载时运行? – adeneo