为什么这个简单的事件监听器不能在Javascript中工作?

时间:2013-12-10 16:54:55

标签: javascript events

我想知道是否有人可以为我提供教学点。我正在尝试学习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>

感谢。

3 个答案:

答案 0 :(得分:2)

开关必须位于事件Listener的函数内:

myButton.addEventListener("click", function() {
    testingVar = "hello";
    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
}, false);

在您的示例中,变量testingVar已初始化,但在执行代码的switch部分时未分配值。

另外,如果你定义了一个default的情况,你会发现在页面加载时调用了这个开关。

答案 1 :(得分:2)

其他答案未能注意到问题的原因,即理解为什么它不起作用。

它不起作用的原因是因为JavaScript的执行方式。

var myvar; // myvar is declared, but not defined yet. myvar === undefined

function foo(){
  myvar = true;
  console.log('EVENT!');
}

// obviously at this point, `foo` has just been declared, not called/executed.

myButton.addEventListener('click', foo);
// foo still hasn't been executed. It has been assigned as handler to be executed whenever a click event is fired

switch(myvar) {  // myvar is still undefined, because foo hasn't been executed
  ...
}

window.setTimeout(function(){
  console.log('Checking myvar');
  console.log(myvar);
}, 5000); // the function defined here will be called after 5 secnds

/* time passes, mouse is clicked */
// now foo is executed
EVENT!
/* 5 seconds have passed, the function in setTimeout is executed */
Checking myvar
true

答案 2 :(得分:0)

试试这个:

<script>
    var myButton = document.getElementById("myButton");
    var testingVar;


myButton.addEventListener("click", function() {
    testingVar = "hello";

    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

}, false);


</script>

作为旁注,通常最好将script代码放入head的{​​{1}}。