单击按钮时没有任何反应

时间:2015-08-10 15:26:55

标签: javascript

我正在尝试创建一个简单的网页,用户输入一个数字,页面告诉用户他们输入的数字是偶数还是奇数。我想在屏幕底部的文本框中显示它。

然而,当我点击按钮时,没有任何反应。我甚至试图在按下按钮时添加“警报”,但即使这样也不会发生。这是代码:

<!DOCTYPE html>  
<html>  
<head>  
<meta charset=utf-8 />  
<title>Compute the factors of a positive integer</title> 
<script type = "text/javascript">
function oddOrEven(){

 var userInput = document.getElementById('number');
 var number = number.value;
 var output = document.getElementById('display');
 alert(number);

 if(number % 2 == 0){
    output.value = number + " is even!"
 }else{
    output.value = number + " is odd!"
 }
 }
</script>     
</head>  
<body>
<form>
Enter a number to check whether it is odd or even: <input type = "text" id = "number"><br>
<button type="button" onclick="oddOrEven()">Click here to check!</button>
<input type = "text" id = "display">
</form>
</body>  
</html>

3 个答案:

答案 0 :(得分:2)

我在你的代码中看到了一些拼写错误,这是我认为应该有效的修改版本:

<!DOCTYPE html>  
<html>  
<head>  
<meta charset=utf-8 />  
<title>Compute the factors of a positive integer</title> 
<script type = "text/javascript">
function oddOrEven(){

 var userInput = document.getElementById('number');
 var number = userInput.value; // you originally had "number.value", but that doesn't make any sense.
 number = parseInt(number); // number is initialy a string, we need to convert it to an integer
 var output = document.getElementById('display');
 alert(number);

 if(number % 2 == 0){
    output.value = number + " is even!"
 }else{
    output.value = number + " is odd!"
 }
 }
</script>     
</head>  
<body>
<form>
Enter a number to check whether it is odd or even: <input type = "text" id = "number"><br>
<button type="button" onclick="oddOrEven()">Click here to check!</button>
<input type = "text" id = "display">
</form>
</body>  
</html>  

答案 1 :(得分:2)

在这里看看这三行:

 var userInput = document.getElementById('number');
 var number = number.value;
 alert(number);

您检索了对#number元素的引用并将其存储在userInput变量中。然后,您创建了一个名为“number”的变量,但是您赋给它的值是您刚刚创建的变量的属性。

但是,存储在number变量中的此对象引用没有此属性,这会导致运行时错误。尝试在浏览器中按下F12并运行此脚本,并查看控制台中显示的错误。

相反,尝试一下,看看你得到了什么反应:

 var userInput = document.getElementById('number');
 var number = userInput.value;
 number = parseInt(number);

答案 2 :(得分:1)

你犯了一个错误。

您写道:

var number = number.value;

你应该写:

var number = userInput.value;