I've been following a YouTube tutorial on how to design your own chatbot for a few hours now and have found myself stuck. Everything is going fine except when I type something to the chatbot it responds to it but doesn't show the message that I've sent to it, also it only show the last message that the chatbot send to me, never any other messages from it or me. Here is a JsFiddle of my chatbot so far Does anyone know why this is happening and what I can do to resolve the problem?

有帮助吗?

解决方案 2

The problem is that you overwrite the current HTML of #container by calling $().html instead of $().append. You should call $().append to add values to the current HTML of the container without overwriting it. You should also add <br> after each attempt to change the HTML of the container to separate the messages by a new line.

Here's your JSFiddle: http://jsfiddle.net/3wySt/10/

Javascript

var username = "";

function send_message(message){
    $("#container").append("<span class=&bot&><b>Chatbot:</b> </span>" + message + "<br>"); //Notice the .append instead of .html and the <br>
}

function get_username(){
    send_message("Hello, what is your name?");
}

function ai(message){
    if (username.length < 3){
        username = message;
        send_message("Nice to meet you " + username + ", how are you doing?");
    }
}

$(function(){

    get_username();

    $("#textbox").keypress(function(event){
        if ( event.which == 13){
            if ( $("#enter").prop("checked") ){

                $("#send").click();
                event.preventDefault();

            }

        }

    });

    $("#send").click(function(){

        var username = "<span class=&quot;username&quot;>You: </span>";

        var newMessage = $("#textbox").val();

        $("#textbox").val("");

        var prevState = $("#container").html();

        if (prevState.length > 3){
            prevState = prevState + "";
        }

        $("#container").html(prevState + username + newMessage + "<br>"); //Notice the <br>

        $("#container").scrollTop($("#container").prop("scrollHeight"));

        ai(newMessage);

    });

});

其他提示

Updated Fiddle: http://jsfiddle.net/3wySt/9/

I have updated your fiddle, the problem was with the following function where it was replacing the entire html instead of appending to it:

function send_message(message){
    $("#container").html("<span class=&bot&><b>Chatbot:</b> </span>" + message);
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top