使用脚本关闭 http://viralpatel.net/blogs/2008/12/set-maxlength-of-textarea-input-using-jquery-javascript.html我试图将文本区域的输入限制为 1000 个字符。原型(prototype)也包含在页面中。
在chrome中运行正常,但在firefox中报如下错误,且输入不限:
$("textarea[maxlength]") is null
我完全被难住了。任何帮助,将不胜感激。代码片段如下。
文本区域:
<%= text_area 'project', 'description', 'cols' => 60, 'rows' => 8, 'maxlength' => 1000 %>
JavaScript:
<%= javascript_include_tag "jquery", "jquery.maxlength" -%>
<script type="text/javascript">
jQuery.noConflict();
jQuery(document).ready(function($) {
$().maxlength();
})
</script>
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
文件包装在这个文件中:
(function($){
.. existing code goes here
})(jQuery);
当您调用 $().maxlength()
时,它试图使用 $
变量,但在不同的范围内,它不再等于 jQuery
。通过将插件包装在一个自执行的匿名函数中,它创建了一个私有(private)范围,其中 $
= jQuery
关于javascript - 使用 jQuery 在 textarea 中设置最大长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2278540/