gpt4 book ai didi

javascript - 事件监听器未触发

转载 作者:行者123 更新时间:2023-11-28 18:56:05 24 4
gpt4 key购买 nike

我有以下代码:

function expandTextarea () {
var textareas = document.getElementsByTagName('textarea');
for (var i = 0; i < textareas.length; i++) {
if (textareas[i].scrollHeight > 100) {
textareas[i].style.height = textareas[i].scrollHeight + 2 + 'px';
} else {
textareas[i].style.height = '100px !important';
}

textareas[i].addEventListener('onchange', adjustTextareaHeight(this));
// textareas[i].addEventListener('keyup', adjustTextareaHeight(textareas[i]));
// textareas[i].addEventListener('paste', adjustTextareaHeight(textareas[i]));
// textareas[i].addEventListener('cut', adjustTextareaHeight(textareas[i]));
}
}

function adjustTextareaHeight (textarea) {
console.log(textarea.length);
if (textarea.length > 0) {
textarea.style.height = textarea.scrollHeight + 2 + 'px';
}
}

由于某种原因,事件监听器永远不会被触发。请注意,expandTextarea 是从我的 window.onload = function () {} 函数调用的。

当我直接调用 expandTextarea 时,它运行时没有任何问题,但是当我进行更改时,按 Enter 键一堆,它永远不会调用 onchange 事件。

最佳答案

您必须将函数传递给addEventListener。目前,您正在传递 undefined,即 adjustTextareaHeight返回值。因此浏览器不知道事件发生时要执行什么。

你想要的是:

textareas[i].addEventListener('change', function() {
adjustTextareaHeight(this);
});
<小时/>

在您的代码中,您立即调用adjustTextareaHeight(而不是在更改时)。 this 可能引用全局对象 (window),并且 window.lengthundefined,这不是 >> 0.

关于javascript - 事件监听器未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33618664/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com