使用javascript设置maxlength [英] setting maxlength using javascript

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

问题描述

我正在尝试使用JavaScript动态设置输入字段的最大长度.显然这是IE中的问题,我找到了解决方案的一部分.

I'm trying to set the maxlength on input fields dynamically using JavaScript. Apparently that is a problem in IE, and I found part of the solution.

$("input#title").get(0).setAttribute("max_length", 25);
$("input#title").get(0).setAttribute(
                        "onkeypress", 
                        "return limitMe(event, this)");

function limitMe(evt, txt) {
    if (evt.which && evt.which == 8) return true;
    else return (txt.value.length < txt.getAttribute("max_length");
}

它可以在Firefox中运行,但由于某些原因不能在IE中运行.但是,它适用于设置如下的输入字段:

It works in Firefox, but not in IE for some reason. However, it works on input fields set like this:

<input type="text" max_length="25" onkeypress="return limitMe(event, this);"/>

但是由于输入字段是动态创建的,所以我不能这样做...有什么想法吗?

But since the input fields are created dynamically, I can't do this... Any ideas?

推荐答案

如果您使用的是jQuery,那么为什么不充分利用其抽象呢?

If you're using jQuery then why not make full use of its abstractions?

例如

代替:

$("input#title").get(0).setAttribute("max_length", 25);
$("input#title").get(0).setAttribute(
                        "onkeypress", 
                        "return limitMe(event, this)");
function limitMe(evt, txt) {
    if (evt.which && evt.which == 8) return true;
    else return (txt.value.length < txt.getAttribute("max_length");
}

执行此操作:

$('input#title').attr('maxLength','25').keypress(limitMe);

function limitMe(e) {
    if (e.keyCode == 8) { return true; }
    return this.value.length < $(this).attr("maxLength");
}


它在IE中不起作用的原因可能是由于您如何通过setAttribute附加了"onKeyPress"处理程序. -这不是注册事件处理程序的正确方法.


The reason it's not working in IE is probably because of how you attached the 'onKeyPress' handler, via setAttribute. - This isn't the proper way to register event handlers.

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

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