2017-05-10 1 views
0

채팅 봇을 만들려고합니다. 이 코드를 실행하면 "TypeError : null은 객체가 아닙니다. (document.getElementById ("message "). value ')"행 11에 있습니다. 코드가 실행되면 사용자는 다음과 같아야합니다. "안녕하세요"를 입력하고 컴퓨터가 그것에 응답 할 수 있습니다. 누구나 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

코드에 약간의 변경을 가하면 작동합니다. 자바 스크립트에서 발생시킬 이벤트와 이벤트 ID를 갖도록 버튼을 변경했습니다.

//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

관련 문제