【问题标题】:.includes Not Finding Period.包括未找到期间
【发布时间】:2018-02-26 22:01:07
【问题描述】:

我有一个 JavaScript 函数,它可以防止用户输入除数字和句点之外的任何字符。我还试图阻止用户输入多个句点。根据我对该脚本工作原理的观察,如果用户输入句点,然后输入数字(“.1”),则在删除第一个句点之前,他们将无法再输入句点。然而,由于某种原因,用户可以键入两个或多个连续句点(“..”)而没有阻止它的功能。有趣的是,这会导致该函数找不到任何小数,从而允许用户输入任意数量的小数。这是我正在使用的代码:

function isNumberKey(evt){
	if (evt.keyCode == 0) {
		var charCode = evt.charCode;
		if (charCode > 31 && (charCode != 46 && (charCode < 48 || charCode > 57))) {
			return false;
		} else {
			if (charCode == 46) {
				if (document.getElementById('inputBox').value.includes(".") == true) {
					return false;
				} else {
					return true;
				}
			} else {
				return true;
			}
		}
	}
}
<form name="form" id="form" onsubmit="calculate(); return false;" accept-charset="utf-8">
  <input type="number" onkeypress="return isNumberKey(event)" value="0" min="0" id="inputBox">
</form>

随意玩。也许我没有使用正确的东西来找到这个时期。我在这里做错了什么?为什么它允许在另一个句点已经存在之后立即键入一个句点?

我不知道这是否与它有关,但我在 Ubuntu 16.04 LTS 上使用最新的 Firefox。

【问题讨论】:

    标签: javascript forms function


    【解决方案1】:

    这是因为您将这个 input 声明为 number,所以 '.'正在从其价值中删除。只需将输入类型更改为text

    function isNumberKey(evt){
    	if (evt.keyCode == 0) {
    		var charCode = evt.charCode;
    		if (charCode > 31 && (charCode != 46 && (charCode < 48 || charCode > 57))) {
    			return false;
    		} else {
    			if (charCode == 46) {
    				if (document.getElementById('inputBox').value.includes(".") == true) {
    					return false;
    				} else {
    					return true;
    				}
    			} else {
    				return true;
    			}
    		}
    	}
    }
    <form name="form" id="form" onsubmit="calculate(); return false;" accept-charset="utf-8">
      <input type="text" onkeypress="return isNumberKey(event)" value="0" min="0" id="inputBox">
    </form>

    【讨论】:

      【解决方案2】:

      您的整个isNumberKey 函数包含在if 语句中,该语句检查事件的keyCode 是否为零。当您键入句点时,keyCode46。所以你的逻辑永远不会被执行。

      另一方面,KeyboardEvent.keyCode 已被弃用;你不应该使用它。 MDN 建议改用KeyboardEvent.key

      正如guijob所说,您还应该将输入的type更改为text

      【讨论】:

      • if语句是函数的内容。它本身不在 if 语句中。 if 语句是逻辑。我用console.log() 测试了keyCode 输出,我选择使用它,因为它有效。当我将KeyboardEvent 的输出写入控制台时,charCode 的值是46,但keyCode 的值在一段时间内是00 表示任何字母,但不是其他键,例如 TabHomeEnd。我添加了该检查以防止与其他键相关的其他错误。
      猜你喜欢
      • 2017-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-11
      • 2015-02-01
      • 1970-01-01
      • 2020-11-22
      • 2017-06-02
      相关资源
      最近更新 更多