addEventListener与onClick属性的缺点

问题描述

| 我了解
addEventListener
onclick
属性间的区别,并且知道如何使用两者。我想知道是否有退缩,总是使用
EventListener
\而不是
onclick
属性。从JavaScript动态生成HTML时,
EventListener
似乎比仅使用using1ѭ至少强大。 有内存/ cpu缺陷吗?还是我只能使用EventListeners安全吗?     

解决方法

这可能不是您要走的方向,但是在某些情况下您将无法删除事件侦听器。 事件处理程序是完全公开的,并且任何人都可以对其进行(在一定程度上)修改:
// You do this
myLink.onclick = function () {
    alert(\'hello,world\');
};

// Another developer who hates you because
// he thinks that you\'re hitting on his girlfriend
// but you\'re not,you\'re just friends,but
// he\'s jealous so he doesn\'t understand
// does this
myLink.onclick = function () {
    alert(\'muahahahaha\');
};

// Someone else could even get rid of
// the handler entirely:
myLink.onclick = null;
但是没有可公开访问的事件侦听器列表。删除事件侦听器的唯一方法是,如果您仍然可以访问原始功能,则:
myLink.addEventListener(\'click\',function () {
    alert(\'hello,world\');
},false);
现在无法删除该事件侦听器。您为它提供了一个匿名函数,因此即使您愿意,也无法将其删除。