2 回答
![?](http://img1.sycdn.imooc.com/54584de700017cbd02200220-100-100.jpg)
TA贡献1893条经验 获得超10个赞
使用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>
![?](http://img1.sycdn.imooc.com/545863cd0001b72a02200220-100-100.jpg)
TA贡献1804条经验 获得超3个赞
您也可以使用 Jquery 并执行以下操作:
$("#examle-button").on("click", function(){
myfunctionone();
myfunctiontwo();
myfunctionthree();
})
添加回答
举报