1

我正在关注教程并具有以下代码:

CSS:

.bot {
    color:#CCCCCC;
    font-weight:bold;
}

Javascript:

function username(){
    $("#container").html("<span class = 'bot'>Chatbot: </span>Hello, what is your name?);
}

$(function(){
    username();
});

我已经彻底遵循了本教程,但不知道为什么代码不起作用。有谁知道是什么问题?

4

2 回答 2

3

您在关闭 html 字符串的函数"中缺少引号:username

function username() {
    $("#container")
        .html("<span class = 'bot'>Chatbot: </span>Hello, what is your name?");
}

$(function() {
    username();
});

像这样的错误将显示在您的浏览器调试控制台中。

于 2014-01-11T13:08:01.243 回答
1

本教程所有相关的jquery代码都需要包含在$(function(){}中

这是一个工作示例:

http://jsfiddle.net/3wySt/5/

和更正的脚本:

var username = "";

function send_message(message) {
    $("#container").html("<span class=&quot;bot&quot;>Chatbot: </span>" + message);
}

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);

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

        ai(newMessage);

    });

});
于 2014-01-12T22:08:37.390 回答