使用 Prototype 事件观察器防止用户在 textarea 中写入超过 N 个字符 [英] Prevent user from writing more than N characters in a textarea using Prototype event observers

查看:47
本文介绍了使用 Prototype 事件观察器防止用户在 textarea 中写入超过 N 个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道可以使用以下技巧从 textarea 上的 input 元素模拟 maxlength 属性:

I am aware that it's possible to emulate the maxlength property from input elements on a textarea by using this trick:

<textarea rows="5" cols="30" onkeydown="return checkLength(this)"></textarea>

<script type="text/javascript">
var maxLength = 30;

function checkLength(elem) {
  if (elem.value.length == maxLength) {
    return false;
  }
  return true;
}
</script>

通过使用 checkLenght 的返回值作为 onkeydown 事件的返回值,我能够有效地防止用户写入超出配置的限制,因为事件链会在输入之前被破坏字母出现.

By using checkLenght's return value as the return value for the onkeydown event, I'm able to effectively prevent the user from writing beyond the configured limit, as the event chain will be broken before the inputted letter appears.

我使用 Prototype 的事件观察器尝试了相同的技术,但没有奏效.这是我尝试过的简化版本:

I've tried the same technique using Prototype's event observers, but it didn't work. Here's a simplified version of what I tried:

<textarea rows="5" cols="30" id="myTextArea"></textarea>

<script type="text/javascript">
var maxLength = 30;

function checkLength() {
  if ($('myTextArea').value.length == maxLength)) {
    return false;
  }
  return true;
}

document.observe('dom:loaded',function(){
  $('myTextArea').observe('keydown',checkLength);
});
</script>

显然,这行不通,因为我无法通过返回 false 来破坏事件链(并且 Event.stop() 只会阻止此事件冒泡,而不会完全停止执行).

Apparently, this won't work because I can't break the event chain by returning false (and Event.stop() will only prevent this event from bubbling up, not stopping execution altogether).

我通过检查 onkeyup 事件上的 textarea 长度并在超出限制时调整其值来解决此问题;但它不一样,因为用户会看到文本出现和消失.

I've workarounded this problem by checking the textarea's length on the onkeyup event and trimming its value if the limit is exceeded; but it isn't the same, as the user will see text appearing and disappearing.

有没有办法达到同样的结果?

Is there a way to achieve the same result?

推荐答案

考虑其他答案和评论.最好进行后期验证,不要接受帖子.

Consider the other answers and comments. Better make a post-validation and just don't accept the post.

尽管如此,以下应该有效(在 FF 和 IE 中有效,在 Opera 中无效.无法检查原因)

Nonetheless the following should work (it does in FF and IE, in Opera it doesn't. Can't be bothered to check why)

<textarea rows="5" cols="30" id="myTextArea"></textarea>
<script type="text/javascript">
    var maxLength = 30;
    Event.observe('myTextArea', 'keydown', function (event) {
        if ($('myTextArea').value.length == maxLength) {
            Event.stop(event);
            return false;
        }
    });
</script>

这篇关于使用 Prototype 事件观察器防止用户在 textarea 中写入超过 N 个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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