使用jQuery的textarea中的最大长度 [英] Maxlength in textarea using jQuery

查看:195
本文介绍了使用jQuery的textarea中的最大长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用脚本 http://viralpatel.net/blogs/2008/12/set-maxlength-of-textarea-input-using-jquery-javascript.html 我试图将textarea的输入限制为1000个字符.页面中还包括原型.

Using the script off http://viralpatel.net/blogs/2008/12/set-maxlength-of-textarea-input-using-jquery-javascript.html I am trying to limit the input of a textarea to 1000 characters. Prototype is also included in the page.

在chrome中可以正常工作,但在Firefox中会给出以下错误,并且输入不受限制:

It works fine in chrome, but in firefox the following error is given and the input is not limited:

$("textarea[maxlength]") is null

我完全迷住了.任何帮助,将不胜感激.代码段如下.

I'm completely stumped. Any help would be appreciated. The code snippets follow.

文本区域:

<%= text_area 'project', 'description', 'cols' => 60, 'rows' => 8, 'maxlength' => 1000 %>

javascript:

The javascript:

<%= javascript_include_tag "jquery", "jquery.maxlength" -%>
<script type="text/javascript">
  jQuery.noConflict();
  jQuery(document).ready(function($) {
    $().maxlength();
  })
</script>

jquery.maxlength.js:

jquery.maxlength.js:

jQuery.fn.maxlength = function(){
    $('textarea[maxlength]').keypress(function(event){
        var key = event.which;
        //all keys including return.
        if(key >= 33 || key == 13) {
            var maxLength = $(this).attr('maxlength');
            var length = this.value.length;
            if(length >= maxLength) {
                event.preventDefault();
            }
        }
    });
}

推荐答案

jquery.maxlength.js文件包装在此文件中:

Wrap your jquery.maxlength.js file in this:

(function($){
   .. existing code goes here
})(jQuery);

当您调用$().maxlength()时,它试图使用$变量,但是作用域不同,并且不再等于jQuery.通过将插件包装在一个自执行的匿名函数中,它将创建一个私有作用域,其中$ = jQuery

When you call $().maxlength() it is trying to use the $ variable, but in a different scope and it no longer is equal to jQuery. By wrapping the plugin in a self executing anonymous function, it creates a private scope where $ = jQuery

这篇关于使用jQuery的textarea中的最大长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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