如何使用JavaScript将最大长度强加于HTML中的textArea我希望有一些功能,如果我写<textarea maxlength="50"></textarea><textarea maxlength="150"></textarea><textarea maxlength="250"></textarea>它将自动将最大长度强加到textArea上。如果可能,请不要在jQuery中提供解决方案。注意:如果我这样做,这是可以做到的:<textarea onkeypress="return imposeMaxLength(event, this, 110);" rows="4" cols="50">function imposeMaxLength(Event, Object, MaxLen)
{
return (Object.value.length <= MaxLen)||(Event.keyCode == 8 ||Event.keyCode==46||(Event.keyCode>=35&&Event.keyCode<=40))
}抄袭在HTML文本区域中模拟HTML输入“maxength”属性的最佳方法是什么?但关键是,我不想每次声明textArea时都写onKeyPress和onKeyUp。
3 回答
白板的微信
TA贡献1883条经验 获得超3个赞
window.onload = function() {
var txts = document.getElementsByTagName('TEXTAREA');
for(var i = 0, l = txts.length; i < l; i++) {
if(/^[0-9]+$/.test(txts[i].getAttribute("maxlength"))) {
var func = function() {
var len = parseInt(this.getAttribute("maxlength"), 10);
if(this.value.length > len) {
alert('Maximum length exceeded: ' + len);
this.value = this.value.substr(0, len);
return false;
}
}
txts[i].onkeyup = func;
txts[i].onblur = func;
}
};}
倚天杖
TA贡献1828条经验 获得超3个赞
更新.live()
$(function() {
// Get all textareas that have a "maxlength" property.
$('textarea[maxlength]').each(function() {
// Store the jQuery object to be more efficient...
var $textarea = $(this);
// Store the maxlength and value of the field.
var maxlength = $textarea.attr('maxlength');
var val = $textarea.val();
// Trim the field if it has content over the maxlength.
$textarea.val(val.slice(0, maxlength));
// Bind the trimming behavior to the "keyup" event.
$textarea.bind('keyup', function() {
$textarea.val($textarea.val().slice(0, maxlength));
});
});});添加回答
举报
0/150
提交
取消
