进行自动实时聊天/虚假聊天,我的javascript跳过了第一个响应

Making a automated live chat / fake chat and my javascript is skipping the first response

本文关键字:聊天 javascript 我的 过了 响应 第一个 实时      更新时间:2023-09-26

我为自动回答问题而编写的一段代码跳过了第一个响应。

我希望它做的另一件事是在发送数组中的最后一条消息后隐藏sendButton。我尝试在消息数组中放入 .hide(),希望它能将其用作禁用按钮的最后一个响应,但这除了弄乱代码之外似乎什么也没做哈哈。

如果有人能帮助我,我将不胜感激!

法典:

$(window).load(function(){
    $(document).ready(function() {
      $("#typing").hide();
      var n = "You:<br>";
      var o = $('#outputWindow');
      var i = $('#inputWindow');
      var s = $('#sendButton');
      var t = $('#typing');      
      var r = 0;
      //arrays
      var msg = ['msg1<br />', 'msg2<br />', 'msg3<br />'];
      //fire send events
      $(s).click(function() {
      runAI();
      });
      $(i).keydown(function(e) {
      if (e.keyCode == 13) {
            runAI();
      }
      });
      function runAI() {
      if (i.val().length > 0) {
            r = r + 1;
            o.html(o.html()+n+$("#inputWindow").val()+"<br><hr>" );      
            setTimeout(function(){ $("#typing").show();  }, 3000);            
            i.val('');
            i.focus();
      }
      }
      i.focus();
    });
<!DOCTYPE html>
<html lang="en">
<title>Automated Chat</title>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.4.2.js'></script>
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
    $(document).ready(function() {
      $("#typing").hide();
      var n = "You:<br>";
      var o = $('#outputWindow');
      var i = $('#inputWindow');
      var s = $('#sendButton');
      var t = $('#typing');      
      var r = 0;
      //arrays
      var msg = ['msg0<br />','msg1<br />', 'msg2<br />', 'msg3<br />'];
      //fire send events
      $(s).click(function() {
          i.hide();
            s.hide();
      runAI();
      });
      $(i).keydown(function(e) {
      if (e.keyCode == 13) {
            runAI();
            i.hide();
            s.hide();
      }
      });
      function runAI() {
      if (i.val().length > 0) {
            r = r + 1;
            o.html(o.html()+n+$("#inputWindow").val()+"<br><hr>" );      
            setTimeout(function(){ $("#typing").show();  }, 1000);            
            setTimeout(function(){ o.html(o.html()+"Username:<br>"+msg[r]+"<hr>") }, 3000);
            setTimeout(function(){ $("#typing").hide();i.show();s.show();i.val(''); i.focus(); }, 3000);

      }
      }
      i.focus();
    });
});//]]>  
</script>
</head>
<body>
    <div class="container">
    <div id="wrapper">
      <div id="outputWindow"></div>
      <input type="text" id="inputWindow"></input>
      <input type="submit" id="sendButton" value="Send Message"/>
      <div id="typing">Username is typing..</div>
    </div>
</body>
</html>

我认为它已经完成了。

我发现了问题所在,我在 OP 中设置 r = 0。我继续将其更改为-1,现在它不再跳过第一个响应。

这是因为它在 OP 中从 1 开始计数而不是 0。