Javascript insertAfter()在我不使用时复制元素';我不想这样

Javascript insertAfter()在我不使用时复制元素';我不想这样,javascript,dom,Javascript,Dom,好吧,我正在做一个聊天机器人,我遇到了一个问题。所以我需要做一个函数,每次按下enter键时创建一条聊天信息。到目前为止,结果很好,只是一个问题。它复制了一个元素,我只想要其中一个 要查看我在说什么,请转到并键入一条消息,然后按enter键。注意有两条“Foo!”消息吗?我只想要一个。我还想让这些消息按时间顺序从上到下传递,但我不能这样做,直到我发现为什么会发生这种重复 function insertAfter(referenceNode, newNode) { referenceNod

好吧,我正在做一个聊天机器人,我遇到了一个问题。所以我需要做一个函数,每次按下enter键时创建一条聊天信息。到目前为止,结果很好,只是一个问题。它复制了一个元素,我只想要其中一个

要查看我在说什么,请转到并键入一条消息,然后按enter键。注意有两条“Foo!”消息吗?我只想要一个。我还想让这些消息按时间顺序从上到下传递,但我不能这样做,直到我发现为什么会发生这种重复

function insertAfter(referenceNode, newNode) {
    referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}

var robotMessage = userMessage;

function intelResponse(){

        // ROBOT
        var robot = document.createElement("h4");
        var robotText = document.createTextNode("Robot");
        robot.appendChild(robotText);
        robot.className = "rtitle";
        document.body.appendChild(robot);
        insertAfter(userMessage, robot);

        // Robot's response
        robotMessage = document.createElement("span");
        var robotMessageText = document.createTextNode("FOO");
        robotMessage.appendChild(robotMessageText);
        robotMessage.className = "rmsg";
        document.body.appendChild(robotMessage);
        insertAfter(robot, robotMessage);

}

您从“提交”例程调用“intelResponse”,也在调用“提交”例程之后显式调用。

您从“提交”例程调用“intelResponse”,也在调用“提交”例程之后显式调用。

问题在于
submitUserResponse
函数的末尾,当您同时调用
intelResponse
时,问题在于
submitUserResponse
函数的末尾,在您同时调用
intelResponse
时,由于您调用了函数两次,因此消息会追加两次

一次键控:

$(document).keyup(function (e) {
    if (e.keyCode == 13) {
        submitUserMessage();
        intelResponse();
        $("#user-input").val("");
    }
});
在提交信息中


注释其中一个,它不会重复:

由于您调用了两次函数,因此消息追加了两次

一次键控:

$(document).keyup(function (e) {
    if (e.keyCode == 13) {
        submitUserMessage();
        intelResponse();
        $("#user-input").val("");
    }
});
在提交信息中


评论其中一个,它不会重复:

一个非常简单的错误。您正在调用方法
intelResponse
两次。修正了这个问题


一个非常简单的错误。您正在调用方法
intelResponse
两次。修正了这个问题


这是因为您要调用
intelResponse
两次。一次在事件处理程序中,一次在
submitUserMessage
函数中。这是因为您调用了
intelResponse
两次。一次进入事件处理程序,一次进入
submitUserMessage
函数。@mattnowstech:开发人员总是遇到一些小问题:D@MattKnowsTech:开发人员总是会遇到一些小问题:D