2013-12-10 46 views
0

我想知道如果有人能为我提供一个教学点。我正在尝试学习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> 

谢谢。

+0

当您点击链接时,'testsVar'将成为'“hello”'。当'testingVar'为空时页面加载后,您的switch语句就立即执行 – Satpal

+0

交换机仅在第一个页面加载时运行? – adeneo

回答

2

开关必须是事件侦听器的函数内:

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被initalized,但没有被执行的代码的部分switch时分配的值。

另外,如果您定义了default大小写,您应该认识到在页面加载时调用了该开关。

+0

这很合理 - 谢谢! –

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代码会在htmlhead

+0

请注意,在关闭body标签之前加载脚本不是更好吗? http://developer.yahoo.com/performance/rules.html#js_bottom – andrei

1

其他答案没有注意到这个问题的理由是为什么它不起作用。

它不工作的原因是因为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 
+1

我认为这是有道理的。感谢您认识到这个问题,并教给我什么时候声明,定义和执行的区别。非常感激 :) –

相关问题