Использование EventTarget.prototype.addEventListener
.
Использование таких встроенных слушателей событий, как вы, обычно считается очень плохой и потенциально вредоносной практикой .
Пример:
// make sure the DOM is parsed before trying to find elements to attach listeners
document.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 listeners
document.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>