javascript中的onkeypress + onblur [英] onkeypress + onblur in javascript

查看:95
本文介绍了javascript中的onkeypress + onblur的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当元素失去焦点时,会触发javascript中的onblur事件。

The onblur event in javascript is triggered when the element loses focus.

onkeydown在按下某个键并且定期发生时具有焦点的元素上发生直到密钥被释放。

The onkeydown Occurs on an element that has the focus when a key is pressed down and occurs periodically until the key is released.

如果我想验证日期字段,onkeydown事件涉及9和13(输入和制表键)。
但是当我按下回车键时,我收到重复的提醒信息。
当然,在这种情况下,我们有两个测试,onblur和onkeydown事件。

If I want to validate a date field, the onkeydown event concerns 9 and 13 (enter and tab key). But when I press the enter key, then I receive duplicate alert message. Of course in this case we have two tests, onblur and onkeydown event.

这是html代码:

<html:text      onblur="return onDateChange(this);"
        onkeydown="return onDateKeyPress(this);"/>

onDateChange()方法是:

the onDateChange() method is :

function onDateChange(obj){
//validateField is an externatl javascript method which trigger an alert message if we have errors in date 
        if(validateField(obj,'date',dateFormat)){
        //do instructions
        }
}

最后onDateKeyPress()方法是:

and finally the onDateKeyPress() method is :

function onDateKeyPress(obj){
    if(window.event.keyCode == 9)
    {  
       if(validateField(obj,'date',dateFormat))
       {
           //do instructions
       }
    }
    if(window.event.keyCode == 13)
    {  
      if(validateField(obj,'date',dateFormat))
      { 
        //do instructions
      }
    }
}

所以,问题是要有一个显示警告消息。
有什么建议吗?

So, the problem is to have one display alert message. Any suggestions?

推荐答案

你可以用jquery轻松完成

you can do it easily with jquery

$('#text_field_id').bind({
  blur: function(event) {
    if(validateField(this,'date',dateFormat)){
        //do instructions
        }
  },
  keydown: function(event) {
    if(event.keyCode == 9)
    {  
       if(validateField(this,'date',dateFormat))
       {
           //do instructions
       }
    }
    if(event.keyCode == 13)
    {  
       if(validateField(this,'date',dateFormat))
       {
           //do instructions
       }
    }

  }
});

您不需要包含 onclick 或<文本元素中的code> onkeydown 。一个小问题,你想在所有情况下执行相同的指令或不同的指令????如果你想执行相同的指令,可以删除很多代码。

you dont need to include onclick or onkeydown in your text element. One small question you want to execute same instructions in all cases or different instructions???? if you want to execute same instructions, lot of codes can be removed.

这篇关于javascript中的onkeypress + onblur的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆