简体   繁体   English

如何通过按 ESC 键(Javascript)来防止中止?

[英]How to prevent abort by pressing ESC key (Javascript)?

I would like to prompt a string.我想提示一个字符串。 My additional need is to not escape by pressing the ENTER or ESC key.我的额外需要是不要通过按 ENTER 或 ESC 键来逃避。 With this method ENTER works (doesn't escape):使用这种方法 ENTER 工作(不逃避):

var f1 = '';
while (f1.length < 1) {
  f1 = prompt('Please give a value of the string!');
}

How can I reach, that this script doesn't escape by pressing ESC either?我怎样才能达到这个脚本也不能通过按 ESC 转义? Thanks, hazazs谢谢,哈兹

You can't.你不能。 prompt is a browser function and its event cannot be prevented. prompt是浏览器 function 并且无法阻止其事件。

Instead, try to create your own popup window for that purpose.相反,尝试为此创建自己的弹出窗口 window。 There are various jQuery/Bootstrap modals available.有各种可用的 jQuery/Bootstrap 模式。

prompt迅速的

shows a message asking the user to input text.显示一条消息,要求用户输入文本。 It returns the text or, if Cancel button or Esc is clicked, null它返回文本,或者,如果单击取消按钮或 Esc,则返回 null

prompt returns null when you click ESC button.当您单击 ESC 按钮时, prompt返回null You need to check null also in while您还需要同时检查 null

while (f1 == null || f1.length < 1)

Or simply或者干脆

while (!f1)

Use this one:使用这个:

var f1 = '';
while (!f1) {
     f1 = prompt('Please give a value of the string!');
}

Note: As Cancel and ESC both returns null, you will not be able to Cancel it though.注意:由于 Cancel 和 ESC 都返回 null,但您将无法取消它。

Easy.简单的。 First you have to give a default value of prompt and set it to prompt and check if the prompt is empty by comparing default value with new one.首先,您必须提供默认值 prompt 并将其设置为 prompt 并通过将默认值与新值进行比较来检查提示是否为空。 If user ignore the prompt the default value is the final value.如果用户忽略提示,则默认值为最终值。 And there we will get it.在那里我们会得到它。 I am returning false to results when user ignores or press enter or esc.当用户忽略或按 enter 或 esc 时,我将结果返回 false。

 document.getElementById("test").addEventListener("click", function() { var oldVal = 'Enter Name:'; var newVal = prompt("Enter new value:", oldVal); var results = document.getElementById("results"); if (newVal === null || newVal === oldVal) { results.innerHTML = false; //And here if the prompt is empty just do what you want. } else { results.innerHTML = true; } });
 <button id="test">Test</button> <div id="results"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM