我试图根据其中的文本量来调整页面上多个textareas的大小。通过替换周围的标签在事件处理程序中创建文本区域:

$('.container').on('click', '.js-post-edit-button', function (e) {
    e.preventDefault();
    const $form = $(this).parentsUntil(".js-post-update-form").parent();
    const $h5 = $form.find(".post-title");
    const $p = $form.find(".post-content");
    $h5.replaceWith($("<textarea/>", {
        "name": "post_edit[title]",
        "class": "form-control js-textarea-content",
        "id": "js-textarea-title",
        "style": "margin-bottom: 20px;",
        "text": $h5.text().replace("\n", "").replace(/\s{2,}/g, " ").trim(),
    }));
    $p.replaceWith($("<textarea/>", {
        "name": "post_edit[description]",
        "class": "form-control js-textarea-content",
        "id": "js-textarea-description",
        "style": "margin-bottom: 20px;",
        "text": $p.text().replace("\n", "").replace(/\s{2,}/g, " ").trim(),
    }));
    resizeTextarea();
});

function resizeTextarea () {
    const textarea = document.getElementsByClassName("form-control js-textarea-content");
    textarea.style.height = 'auto';
    textarea.style.height = text.scrollHeight+'px';
}


当我单击编辑按钮(js-post-edit-button)时,出现以下错误:

Uncaught TypeError: Cannot set property 'height' of undefined


谁能告诉我为什么我会收到此错误?

最佳答案

NewToJS几乎已经给了您答案。我会尝试增加一些细微差别。

为什么编码不起作用

根据MDN documentation getElementsByClassName()返回一个HTMLCollection(元素列表)。


您正在尝试从此集合的另一个属性(样式)访问一个属性(高度)。因为属性'style'在HTMLCollection上不存在,这将返回undefined
现在,您正在尝试更改此属性的“高度”属性。


那应该解释为什么您得到错误:

Uncaught TypeError: Cannot set property 'height' of undefined


替代方法

我只是将函数更改为接受元素作为参数。

function resizeTextarea ( textarea ) {
    textarea.style.height = 'auto';
    textarea.style.height = text.scrollHeight+'px';
}


您还可以使用更多的OOP方法,并向HTMLTextAreaElement.prototype添加新方法。我想无论你喜欢什么。

现在您可以根据需要获取元素


我不建议使用getElementsByClassName()[0]。它可能在大多数时间都有效,但是当该类在页面上多次存在时,可能会导致意外情况。
如果您100%确定该元素在页面上仅出现一次,则最好使用document.getElementById()
在javascript中生成元素时,可以使用对该元素的引用。

10-06 15:18