更改动态创建的文本区域的高度

Change height of dynamically created textarea

$("#btnwrite").click(function(){
        $(".sent").after("<textarea class='write'></textarea>");
});

这会在每个 sent 段落后创建一个文本区域。
现在,我想在用户输入时调整文本区域的高度:

function h(e) {
    $(e).css({'height':'auto','overflow-y':'hidden'}).height(e.scrollHeight);
}
$('textarea').each(function () {
  h(this);
}).on('input', function () {
  h(this);
});

如果 textarea 位于起始 DOM 内,这将完美运行,但不适用于动态创建的 textareas。

将其更改为使用委托事件处理程序

function h() {
    $(this).css({'height':'auto','overflow-y':'hidden'}).height(this.scrollHeight);
}

$(document).on('input', 'textarea', h).trigger('input');