javascript - 使用javascript设置最大长度

标签 javascript html forms

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

$("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 中无效。但是,它适用于这样设置的输入字段:

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

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

最佳答案

如果您正在使用 jQuery 那么为什么不充分利用它的抽象呢?

例如

代替:

$("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' 处理程序。 - 这不是注册事件处理程序的正确方法。

关于javascript - 使用javascript设置最大长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/633876/

相关文章:

javascript - 图像源 uri 内的 if 语句 - React Native

javascript - Angulartics 不会跟踪我在按钮或链接上的事件

javascript - 如何获取 html 表中选定行的值并使用 javascript 在输入文本中显示它们?

python - 用 Python 处理 HTML 表单数据?

javascript - 如何创建弹出窗口来提交表单数据?

PHP JSON 解析,只显示三个参数之一

javascript - JQuery .show() 和 .hide() 无法正常工作

html - 为什么我在 CSS 中的缓动过渡不起作用?

python - HTML 到 PDF 尺寸不正确

javascript - 按品牌一一展示产品系列