当我们从文本框中按 Enter 键时,在单个 jQuery 方法中处理多个操作

Handle multiple operations inside a single jQuery method when we press Enterkey from a textbox

我想在一个文本框中输入文本后单击回车键时处理两个操作。 两个操作是

  1. 将光标移动到下一个文本框
  2. 使用php代码建立串口通信

$(function() {
  $('input:text:first').focus();
  var $inp = $('input:text');
  $inp.bind('keydown', function(e) {
    //var key = (e.keyCode ? e.keyCode : e.charCode);
    var key = e.which;
    if (key == 13) { // Enter key is pressed
      e.preventDefault(); // Prevent the default behaviour of enter key
      var nxtIdx = $inp.index(this) + 1;
      $(":input:text:eq(" + nxtIdx + ")").focus();
      // Ajax query to send request to php
      var test = $("#command-text").val();
      var inputtext = test;
      var command = "1";
      // var mode = $(".common-input mb-20").val();
      $.ajax({
        type: "POST",
        url: "controller.php",
        data: {
          inputtext: inputtext,
          command: command
        },
        cache: false,
        success: function(html) {
          var feedback = "@" + $("#command-text").val() + "#";
          $("#feedback").val(feedback);
        }
      });
    }
  });
});

当我尝试使用以下代码时,只有一个操作正在执行,光标将移动到下一个文本框或建立通信。 请帮我解决这个问题 我试过的代码如下

您使用的语法不正确您的括号位置不正确试试这个:

$(function() {
  $('input:text:first').focus();
  var $inp = $('input:text');
  $inp.bind('keydown', function(e) {
    //var key = (e.keyCode ? e.keyCode : e.charCode);
    var key = e.which;
    if (key == 13) { // Enter key is pressed
      e.preventDefault(); // Prevent the default behaviour of enter key
      var nxtIdx = $inp.index(this) + 1;
      $(":input:text:eq(" + nxtIdx + ")").focus();
      // Ajax query to send request to php
      var test = $("#command-text").val();
      var inputtext = test;
      var command = "1";
      // var mode = $(".common-input mb-20").val();
      $.ajax({
        type: "POST",
        url: "controller.php",
        data: {
          inputtext: inputtext,
          command: command
        },
        cache: false,
        success: function(html) {
          var feedback = "@" + $("#command-text").val() + "#";
          $("#feedback").val(feedback);
        }
      });
    }
  });
});