我是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>
答案 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>