白猪掌柜的
使用EventTarget.prototype.addEventListener.像您一样使用内联事件侦听器通常被认为是一种非常糟糕且可能是恶意的做法。例子:// make sure the DOM is parsed before trying to find elements to attach listenersdocument.addEventListener('DOMContentLoaded', function() { // find the element to attach the listeners to const btn = document.getElementById('example-button'); // create an array with references of your handlers const handlers = [handler1, handler2, handler3]; // for each handler in that array, add is as a listener to the element for (const handler of handlers) { btn.addEventListener('click', handler); }});function handler1(event) { console.log('handler 1 says: ' + event.target.textContent);}function handler2(event) { console.log('handler 2 says: ' + event.target.tagName);}function handler3(event) { console.log('handler 3 says: ' + event.target.id);}<button id="example-button">Example button, click me</button>这也允许在需要时删除任何一个或多个这些侦听器:// make sure the DOM is parsed before trying to find elements to attach listenersdocument.addEventListener('DOMContentLoaded', function() { const btn = document.getElementById('example-button'); for (const checkbox of document.querySelectorAll('input[type=checkbox][id^=handler]')) { checkbox.addEventListener('change', function() { const handler = window[this.id.replace('toggle', '')]; btn[`${this.checked ? 'add' : 'remove'}EventListener`]('click', handler); }) }});function handler1(event) { console.log('handler 1 says: ' + event.target.textContent);}function handler2(event) { console.log('handler 2 says: ' + event.target.tagName);}function handler3(event) { console.log('handler 3 says: ' + event.target.id);}[id^=handler] + label::after { content: 'off'; }[id^=handler]:checked + label::after { content: 'on'; }<button id="example-button">Example button, click me</button><br /><hr /><input type="checkbox" id="handler1toggle" /> <label for="handler1toggle">handler 1 </label><input type="checkbox" id="handler2toggle" /> <label for="handler2toggle">handler 2 </label><input type="checkbox" id="handler3toggle" /> <label for="handler3toggle">handler 3 </label>