【问题标题】:JQuery AutoGrow plugin non effective after AJAX functionJQuery AutoGrow 插件在 AJAX 功能后无效
【发布时间】:2011-12-27 15:56:03
【问题描述】:

jQuery autogrow 插件扩展 textarea 以适应其内容。函数如下。

(function($) {
    /*
     * Auto-growing textareas; technique ripped from Facebook
     */
    $.fn.autogrow = function(options) {

        this.filter('textarea').each(function() {

            var $this       = $(this),
                minHeight   = $this.height(),
                lineHeight  = $this.css('lineHeight');

            var shadow = $('<div></div>').css({
                position:   'absolute',
                top:        -10000,
                left:       -10000,
                width:      $(this).width(),
                fontSize:   $this.css('fontSize'),
                fontFamily: $this.css('fontFamily'),
                lineHeight: $this.css('lineHeight'),
                resize:     'none'
            }).appendTo(document.body);

            var update = function() {

                var val = this.value.replace(/</g, '&lt;')
                                    .replace(/>/g, '&gt;')
                                    .replace(/&/g, '&amp;')
                                    .replace(/\n/g, '<br/>');

                shadow.html(val);
                $(this).css('height', Math.max(shadow.height() + 20, minHeight));
            }

            $(this).change(update).keyup(update).keydown(update);

            update.apply(this);

        });

        return this;

    }

})(jQuery);

然后触发$('textarea').autogrow();。在一个 JQuery 加载函数之后,我们在一个新的文本区域中加载。因此我触发了这个。

$('.commentslogic').load(window.location.href + ' .commentslogic .inner', function(){
$('textarea').autogrow();
}); 

但它不适用于新的textarea,而且在FireBug中也没有报错。救命!

提琴迪迪提琴迪达姆http://jsfiddle.net/JTmND/8/

【问题讨论】:

  • 发布这段代码的 jsFiddle 会很有帮助。
  • 如果我没记错的话,js fiddle 不支持 AJAX 调用。如果我错了,请指出
  • @JoshSmith 模拟小提琴jsfiddle.net/JTmND/8
  • 很高兴你知道了。 jsFiddle 确实在左侧边栏中提供了一个用于测试 AJAX 请求的接口,以供将来参考。

标签: jquery textarea autogrow


【解决方案1】:

在 cmets 中发现,这个小提琴是解决方案:http://jsfiddle.net/JTmND/11/

$(document).ready(function() {
    $('textarea').autogrow();

    $('.button').click(function() {
        $('.test').html('<textarea></textarea>');
        $('.test').find('textarea').autogrow();
    });
});

不管如何将新的文本区域添加到 dom(手动或通过 ajax 回调方法),都需要使用 jquery 选择器来分配自动增长功能。

【讨论】:

  • 还有$('textarea').triggerHandler('change'); ?
  • 您的小提琴没有模拟问题。这是我的。 jsfiddle.net/JTmND/8
猜你喜欢
  • 2011-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多