2017-05-10 48 views
0

我正在嘗試創建一個chatbot。當我運行這段代碼時,我得到一個錯誤,說:「在第11行,TypeError:null不是一個對象(評估'document.getElementById(」message「)。value')」。當代碼運行時,用戶應該能夠輸入「hi」並讓電腦對此作出響應。任何人都可以告訴我第11行有什麼問題嗎?這裏的代碼:Chatbot執行代碼的問題

<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

我對你的代碼做了一些細微的改變,它的工作原理。我改變了這個按鈕來讓一個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>

希望這有助於

+0

太謝謝你了!我一直在努力解決這個問題,並最終解決了問題。現在我可以繼續編寫不同消息的響應。 – GGamer