调用了两次HTML输入事件

HTML input event called twice

本文关键字:两次 HTML 输入 入事件 调用      更新时间:2023-09-26

我的html/javascript代码有问题,代码应该格式化键盘上的数字(1->0.01,2->0.12,3->1.23…6->1234.56)。

似乎子字符串和子字符串的结果被追加了两次。在调试中它工作得很好,但没有调试就不行。(1->0.011,2->1.122,3->112.233)它对删除或退格的作用相同。

这是代码:

formatElementAmount = function(f, d) {
  d = d.replace(/'./g, '');
  d = d.replace(/',/g, '');
  d = parseFloat(d);
  d = d + '';
  var c = document.getElementById((f.target || f.srcElement).id);
  var b = '0123456789';
  var a = f.which || f.keyCode;
  if (a == 13) { // keycode 13 = enter >
    return false;
  }
  if (a == 9) { // keycode 9 == tab
    return true;
  }
  if (a == 8 || a == 46) { // keyCode 8 == backspace, 46 == delete
    if (d.length > 0) {
      d = d.substring(0, d.length - 1);
      c.value = '';
    }
    c.value = format(d);
    return false;
  }
  if (c.value.length > 12) {
    c.value = '';
    c.value = format(d);
    return false;
  }
  if (a >= 96 && a <= 105) { // 96 = numbpad 0, 105 = numpad 9
    a = a - 48;
  }
  key = String.fromCharCode(a);
  if (b.indexOf(key) == -1) {
    return false;
  }
  if ((d.length == 0) && (key == '0')) {} else {
    d = d + key;
  }
  c.value = '';
  c.value = format(d);
  return false;
};
format = function(f) {
  if (f.length == 0) {
    return '0.00';
  }
  if (f.length == 1) {
    return '0.0' + f;
  }
  if (f.length == 2) {
    return '0.' + f;
  }
  var a, b, c, d, e;
  if (f.length > 2) {
    a = '';
    for (c = 0, d = f.length - 3; d >= 0; d--) {
      if (c == 3) {
        a += ',';
        c = 0;
      }
      a += f.charAt(d);
      c++;
    }
    b = '';
    len2 = a.length;
    for (d = len2 - 1; d >= 0; d--) {
      b += a.charAt(d);
    }
    e = f.substr(f.length - 2);
    b += '.' + e;
  }
  return b;
};
<input id="paymentForm" name="paymentForm" type="text" value="0.00" onkeydown="if(this.value =='') this.value ='0.00';
                            if (!formatElementAmount(event, this.value)) {
                                event.stopPropagation();
                            }"></input>

当前代码的问题是它不能阻止keyDown事件的默认操作:

if (!formatElementAmount(event, this.value)) {
    event.stopPropagation();
    event.preventDefault();
}

首先,您应该停止使用event.stopPropagation()——它不会停止默认事件。也不要使用不推荐使用的event.preventDefault()。相反,使用return false禁用默认事件效果并停止从键盘插入字符。也使用keypress事件而不是keydown(我无法解释为什么它有效,因为我不知道)。

<input id="paymentForm" name="paymentForm" type="text" value="0.00" onkeypress="if(this.value =='') this.value ='0.00';
                            if (!formatElementAmount(event, this.value)) {
                                return false;
                            }"></input>

我在Firefox、IE10&我电脑上的Edge。