为什么我的eventListener永远不会开火?

时间:2015-11-09 21:29:53

标签: javascript dom javascript-events

我有以下代码,

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';
    }
}

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

当我直接调用expandTextarea时,它运行没有任何问题但是当我进行更改时,按下输入一串,它从不调用onchange事件。

1 个答案:

答案 0 :(得分:3)

您必须将功能传递给addEventListener。目前,您正在传递undefinedadjustTextareaHeight返回值。因此,当事件发生时,浏览器不知道要执行什么。

你想要的是:

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

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