我正在尝试使用 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/