我正在尝试创建一个聊天机器人。当我运行这段代码时,我得到一个错误说," TypeError:null不是一个对象(评估' document.getElementById(" message")。value')&# 34;第11行。当代码运行时,用户应该可以输入" hi"让计算机回应它。谁能告诉我第11行有什么问题?这是代码:
<html>
<!--Create text box for player to type in-->
<input type="text" id=“messageâ€>
<!--Create paragraph to show chatbot's messages-->
<p id="chatbotText"></p>
<!--Create button to send messages to chatbot-->
<button onclick="input()">Send</button>
<script>
//function to process user messages
var input = function() {
var message = document.getElementById("message").value;
//create array with list of phrases to use in response to "Hello"
var helloMessages = ["Hello.", "Hi.", "Hello!", "Hi!", "Hello. How are you doing?", "Hi. How are you?"];
//function to pick random phrase
function randomWord(arr) {
return arr[Math.floor(Math.random() * arr.length)];
}
if(message === "hi" || message === "hello" || message === "hi!" || message === "hello!" || message === "hi." || message === "hello." || message === "hey." || message === "hey" || message === "hey!") {
document.getElementById('chatbotText').innerHTML = "<p>randomWord(helloMessages)</p>";
}
}
</script>
</html>
答案 0 :(得分:0)
我对您的代码进行了一些细微的更改,但它确实有效。我将按钮更改为具有ID并从JavaScript中引发事件。
//function to process user messages
var button = document.getElementById("btnSubmit")
button.onclick = function() {
var message = document.getElementById("message").value;
//create array with list of phrases to use in response to "Hello"
var helloMessages = ["Hello.", "Hi.", "Hello!", "Hi!", "Hello. How are you doing?", "Hi. How are you?"];
//function to pick random phrase
function randomWord(arr) {
return arr[Math.floor(Math.random() * arr.length)];
}
if (message === "hi" || message === "hello" || message === "hi!" || message === "hello!" || message === "hi." || message === "hello." || message === "hey." || message === "hey" || message === "hey!") {
document.getElementById('chatbotText').innerHTML = "<p>randomWord(helloMessages)</p>";
}
}
<!--Create text box for player to type in-->
<input type="text" id="message">
<!--Create paragraph to show chatbot's messages-->
<p id="chatbotText"></p>
<!--Create button to send messages to chatbot-->
<button id="btnSubmit">Send</button>
希望这有帮助