值更改时的javascript文本框调用事件 [英] javascript textbox call event when value changes

查看:58
本文介绍了值更改时的javascript文本框调用事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本框,每当框的值发生变化时,我想查看是否输入了20位数。

I have a textbox, and whenever the value of the box changes, I want to check and see if 20 digits have been entered.

我以为我会使用onChange事件,但这似乎被解释为IE上的onBlur事件。

I thought that I would use the onChange event, but this seems to be interpreted as the onBlur event on IE.

那么我以为我会使用onKeyDown,但如果用户问题就出现了想要将值粘贴到字段中,然后函数永远不会被调用。

So then I thought I would use onKeyDown, but the problem comes in if the user wants to paste a value into the field, then the function never gets called.

没有其他表单框,所以我不能依赖onBlur或期望他们会改变焦点。

There are no other form boxes so I can't rely on onBlur or expect that they will change focus ever.

我该怎么做?

我只想评估文本框的值每次文本框的值更改。

I just want to evaluate the value of the textbox everytime the value of the textbox changes.

<input type="text" onKeyDown="myfunction()">


推荐答案

一种有效的方法是使用<$的组合c $ c> onkeydown 和 onpaste ,可在IE,Firefox,Chrome和Safari中使用。 Opera在这里很奇怪,因为它不支持 onpaste 所以你可能不得不回到 onchange for Opera或使用 DOMAttrModified 突变事件,请参阅下面的示例。

An effective way is to use a combination of onkeydown and onpaste, which will work in IE, Firefox, Chrome and Safari. Opera is the odd one out here because it doesn't support onpaste so you may have to fall back to onchange for Opera or use the DOMAttrModified mutation event, see example below.

Internet Explorer还支持 onpropertychange ,每次属性更改元素时都会触发 - 包括。我已经读过Opera和Safari支持 DOMAttrModified (不确定Firefox),所以你可以将它与IE的 onpropertychange结合使用(未经测试):

Internet Explorer also supports onpropertychange, which will fire every time a property changes on an element -- including value. I have read that DOMAttrModified is supported by Opera and Safari (not sure about Firefox), so you could use that in combination with IE's onpropertychange (untested):

if ("implementation" in document &&
                   document.implementation.hasFeature('MutationEvents','2.0'))
    myInput.addEventListener("DOMAttrModified", valueChanged, false);    
else if ("onpropertychange" in myInput)
    myInput.onpropertychange = valueChanged;

function valueChanged (evt)
{
    var attr;
    evt = evt || window.event;
    attr = evt.attrName || evt.propertyName;

    if (attr == "value")
        validate();
}

这篇关于值更改时的javascript文本框调用事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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