我正在尝试使用 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 那么为什么不充分利用它的抽象呢?
E.g.
代替:
$("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");
}
Do this:
$('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”处理程序。 - 这不是注册事件处理程序的正确方法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)