在Enter(JavaScript)上输入文本的返回值

时间:2014-05-16 00:49:11

标签: javascript

当用户按下回车按钮时,我想将文本输入的值传递给switch语句。我想这样做而不使用按钮提交。我有一个用户可以在文本字段中输入的命令的简短列表,而switch语句的结果现在只是记录到控制台。

编辑:我还应该提一下,我正在尝试使用纯JS来构建它。

var cmdValue = document.getElementById('cmdLine').value;

switch(cmdValue){
    case "jump":
        console.log("FTL Jump to new system: SUCCESS");
        break;
    case "refuel":
        console.log("Refuel: SUCCESS");
        break;
    case "repair":
        console.log("Repair: SUCCESS");
    default:
        console.log("Command not recognized");
}

Here is the Fiddle

3 个答案:

答案 0 :(得分:0)

在Jquery ......

$(document).keypress(function(e) {
    if(e.which == 13) {
        //whatever
    }
});

答案 1 :(得分:0)

JSFiddle

这或多或少是你想要的。您需要将一个事件处理程序附加到输入并向其传递一个包含switch语句逻辑的函数:

window.onload = function() {
  var cli = document.getElementById('cmdLine');

  // Add event listener on the 'keyup' event to execute the command
  cli.addEventListener('keyup', executeCommand);

  function executeCommand(e) {
    var cmdValue = cli.value;   // get the current value of the cli
    if (e.keyCode === 13) {     // if key equals 'enter'
      switch(cmdValue){
          case "jump":
              console.log("FTL Jump to new system: SUCCESS");
              break;
          case "refuel":
              console.log("Refuel: SUCCESS");
              break;
          case "repair":
              console.log("Repair: SUCCESS");
          default:
              console.log("Command not recognized");
      }
    }
  }
}

答案 2 :(得分:-1)

你需要注册一个回调函数,只要按下键盘上的键并且你的逻辑必须在那个函数中(或者从这个回调函数中调用的其他函数),就会被调用,就像这样

document.getElementById("cmdLine").addEventListener('keydown', function (event) {
    if (event.keyCode === 13) {
        var cmdValue = document.getElementById('cmdLine').value;

        switch (cmdValue) {
            case "jump":
                console.log("FTL Jump to new system: SUCCESS");
                break;
            case "refuel":
            case "repair":
                console.log("Refuel: SUCCESS");
                break;
            default:
                console.log("Command not recognized");
        }

    }
});

Updated jsfiddle