Javascript如果不起作用

时间:2017-08-26 19:26:16

标签: javascript

我是javascript的新手,我正在编写一个简单的程序来回复 但是if语句不起作用。 这是我的代码:

var myInput = document.getElementById('myInput');
var myBtn = document.getElementById('btn');
var value = document.getElementById('myInput').value;
var answer = document.getElementById('answer');
var question = "Hi";

function message() {
  if ( value == question) {
   answer.innerHTML = "Hi, how can i help you?";
  } else {
   answer.innerHTML = "Hi ...";
  }
}

这里是html部分:

<input id="myInput" type="text">
<button id="myBtn" type="button" onclick="message()">Send!</button>
<p id="answer"></p>

2 个答案:

答案 0 :(得分:1)

问题是您在有机会填写之前获取该值。

而是在message函数中获取它。

var myInput = document.getElementById('myInput');
var myBtn = document.getElementById('btn');
var answer = document.getElementById('answer');
var question = "Hi";

function message() {
  var value = document.getElementById('myInput').value;
  if (value == question) {
    answer.innerHTML = "Hi, how can i help you?";
  } else {
    answer.innerHTML = "Hi ...";
  }
}
<input id="myInput" type="text">
<button id="myBtn" type="button" onclick="message()">Send!</button>
<p id="answer"></p>

答案 1 :(得分:0)

var value = document.getElementById('myInput').value; 放在按钮点击功能

<强>样本

var myInput = document.getElementById('myInput');
var myBtn = document.getElementById('btn');

var answer = document.getElementById('answer');
var question = "Hi";

function message() {
   var value = document.getElementById('myInput').value;
  console.log(value);
  console.log(question);
  if (value === question) {
   answer.innerHTML = "Hi, how can i help you?";
  } else {
   answer.innerHTML = "Hi ...";
  }
}
<input id="myInput" type="text">
<button id="myBtn" type="button" onclick="message()">Send!</button>
<p id="answer"></p>