js中出现addEventListener is not a function

js中出现addEventListener is not a function

textarea.addEventListener is not a function

业务场景:
https://juejin.cn/post/6978721383983530015


报错截图:

在这里插入图片描述

原因分析:

js中出现addEventListener is not a function,多半是侦听事件的事件源不对,事件源应该是一个元素,而非数组。

getElementsByClassNamegetElementByTagName()获取到的都是数组,即使满足条件的元素只有一个,也是数组。
因此在事件监听时,必须加[0],否则会报如下错误


解决办法:

// autoHeightTextarea();//textarea 自动撑高
    var textarea = document.getElementsByClassName('autoh');
    textarea[0].addEventListener('input', (e) => {
    
    
        textarea[0].style.height = '180px';
        textarea[0].style.height = e.target.scrollHeight + 'px!important';
        // console.log(e);
    });

参考文章:
https://blog.csdn.net/weixin_47417033/article/details/124261891

猜你喜欢

转载自blog.csdn.net/qq_35393869/article/details/128702013