输入输入类型编号时如何防止“0”作为第一个字符?

ded*_*ono 4 html javascript jquery keycode

我想防止 0 作为第一个字符。但是当我再次focusout和focusin时,我在第一个添加“2”,它仍然运行,我想不应该运行。

这是我的 HTML

<input type="number" id="test">
Run Code Online (Sandbox Code Playgroud)

我的JS

$('#test').keypress(function(evt) {
  if (evt.which == "0".charCodeAt(0) && $(this).val().trim() == "") {
  return false;
   }
});
Run Code Online (Sandbox Code Playgroud)

有人帮助或建议我该怎么办?谢谢你。

gue*_*314 8

您可以使用input事件,也可以用来处理粘贴值,String.prototype.replace()RegExp /^0/取代所有0字符中发现的.value元素

$("#test").on("input", function() {
  if (/^0/.test(this.value)) {
    this.value = this.value.replace(/^0/, "")
  }
})
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<input type="number" id="test">
Run Code Online (Sandbox Code Playgroud)