【问题标题】:why does my eventListener never fire?为什么我的 eventListener 永远不会触发?
【发布时间】:2016-02-10 15:53:14
【问题描述】:

我有以下代码,

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 事件。

【问题讨论】:

  • 这个问题大概有一百个重复。

标签: javascript dom javascript-events


【解决方案1】:

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

你想要的是:

textareas[i].addEventListener('change', function() {
  adjustTextareaHeight(this);
});

在您的代码中,您立即调用adjustTextareaHeight(而不是更改)。 this 可能指的是全局对象 (window),window.lengthundefined,而不是 &gt; 0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-26
    • 2014-09-15
    • 2014-08-02
    • 2014-05-15
    • 1970-01-01
    • 1970-01-01
    • 2015-08-28
    • 1970-01-01
    相关资源
    最近更新 更多