[英]Getting user input in javascript without using prompt
我有一个设置,允许用户在常规的html文本字段中键入命令。 我在文本字段上处理onkeypress事件,检查它是否是已按下的Enter键,然后解析并执行命令。
例如:
deletefile /testfolder/testfile.html
代码看起来像这样:
inputControl.onkeypress = function(e) {
if (e.which == 13) {
var outputMessage = commandHandler.executeCommand(inputControl.value);
printOutputToScreen(outputMessage);
inputControl.value = "";
inputControl.focus();
}
}
(顺便说一下,这并不是我的代码真正的样子,这只是一个示例)
这里的想法是能够编写命令,查看输出,编写另一个命令,查看输出等。
executeCommand解析命令字符串,并使用适当的参数调用特定命令。
> deletefile /test1.html
The file was deleted
> deletefile /test2.html
An error occured while trying to delete the file
这部分很简单。 我需要帮助的是:如果用户仅键入“ deletefile”,我希望能够(使用outputarea)询问用户“您要删除哪个文件?”。
我知道我可以做到:
var additionalInput = prompt("Which file?");
,但我不想使用提示。
忘了我做作的例子,没有人知道在javascript中间要求用户输入的一种好方法(不使用提示),例如:
var status = doSomeStuff(args);
if (status.fail) {
tmp = getUserInput();
doSomeFinalStuffBasedOnTheUserInput(tmp);
}
这有可能吗?
我不确定我是否可以在这里解释自己,但是如果有人认为他们可以以某种方式帮助我,请告诉我:-)
一种解决方案是实现全局状态变量,并将其用作keypress-eventhandler中的一种机制,以将输入路由到命令,例如:
inputControl.onkeypress = function(e) {
if (e.which == 13) {
if (state.additionalInputPending && currentCommand != null) {
currentCommand.executeWithAdditionalInput();
} else {
// perform regular command execution
}
}
}
这样,我的“ app”需要处理内部状态变量,并在按键之间存储currentCommand。
您可以使用jquery / javascript解决方案,在其中显示“花式”对话框(而不是JS提示)以要求输入。
http://trentrichardson.com/Impromptu/#Examples最后一个示例显示表单。 Impromptu只是许多对话框/提示替代方法的解决方案之一。
想到的唯一其他选择是直接在您正在创建的JS控制台中执行此操作,更像是一个真正的命令行工具。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.