【问题标题】:javascript Uncaught ReferenceError: e is not definedjavascript Uncaught ReferenceError: e 未定义
【发布时间】:2014-06-25 11:30:34
【问题描述】:

我收到 Uncaught ReferenceError: e is not defined

输入栏

<input class="form-control text-right" name="amount" maxlength="45" value="${exp.Amount}" onkeyup='evMoneyFormat( e );'  required="required">

脚本

<script type="text/javascript">

function evMoneyFormat(evt) {
    //--- only accepts accepts number and 2 decimal place value
    var theEvent = evt || window.event;
    var key = theEvent.keyCode || theEvent.which;
    key = String.fromCharCode(key);
    var regex = /^[0-9]{1,14}\.[0-9]{0,2}$/; // number with 2 decimal places
    if (!regex.test(key)) {
        theEvent.returnValue = false;
        //--- this prevents the character from being displayed
        if (theEvent.preventDefault) theEvent.preventDefault();
    }
}
 </script>

我该如何解决这个问题?

【问题讨论】:

  • 那么,e 在那里做什么?我建议添加事件 in JavaScript
  • 这里还需要e吗?

标签: javascript jquery


【解决方案1】:

我认为应该是(事件对象在内联上下文中可用event 而不是e

onkeyup='evMoneyFormat( event );'

由于您已使用 jQuery 标记它,因此请使用 jQuery 事件处理程序而不是内联事件处理程序

【讨论】:

  • 如果 OP 没有在任何地方定义变量 event,这仍然不会做任何事情。
  • 对不起,我的意思是没有必要:将event 传递给处理程序无效。
【解决方案2】:

您无需向onkeyup 传递任何内容。

应该是:onkeyup='evMoneyFormat()';

当你的处理程序被调用时,如果你已经为你的函数提供了一个参数(你有:evt),那么事件数据将自动分配给参数。

然后,您可以在处理程序中使用 evt 来获取事件数据。

然而,看到你用 jQuery 标记了这个,一个更简单的方法是:

$(".form-control text-right").keyup(function(evt){
  //--- only accepts accepts number and 2 decimal place value
  var theEvent = evt || window.event;
  var key = theEvent.keyCode || theEvent.which;
  key = String.fromCharCode(key);
  var regex = /^[0-9]{1,14}\.[0-9]{0,2}$/; // number with 2 decimal places
  if (!regex.test(key)) {
      theEvent.returnValue = false;
      //--- this prevents the character from being displayed
      if (theEvent.preventDefault) theEvent.preventDefault();
  }
});

【讨论】:

  • 感谢您的回答。现在我没有收到Uncaught ReferenceError: e is not defined.。但此验证不起作用。我只需要输入 100、120.25 等数字。但是当我在字段中输入字母时,它们也会显示出来。我的代码错了吗?
  • @Bishan 我相信这比in comments 更好地在单独的问题中提出。
  • @Bishan 您的正则表达式适用于整个字段,而不是单个按键。
猜你喜欢
  • 1970-01-01
  • 2016-11-05
  • 1970-01-01
  • 2012-10-11
  • 2017-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多