猿问

在同一个 div 元素上添加多个 onclick 操作的最佳实践是什么

我确实明白这是一种突兀的方式,但我正在实施的方式已经走了很长一段路,所以我现在无法真正改变,我使用的方法有时有效,其他方法只作用于最后的点击操作,我想要一种模式它可以正常工作,请在代码之前参考以查看我如何添加 onclick 操作。我想知道为什么它有时有效,而在其他时候却无法全部执行

<button onclick="myfunctionone(); myfunctiontwo(); myfunctionthree();">click here</button>


摇曳的蔷薇
浏览 237回答 2
2回答

白猪掌柜的

使用EventTarget.prototype.addEventListener.像您一样使用内联事件侦听器通常被认为是一种非常糟糕且可能是恶意的做法。例子:// make sure the DOM is parsed before trying to find elements to attach listenersdocument.addEventListener('DOMContentLoaded', function() {&nbsp; // find the element to attach the listeners to&nbsp; const btn = document.getElementById('example-button');&nbsp; // create an array with references of your handlers&nbsp; const handlers = [handler1, handler2, handler3];&nbsp; // for each handler in that array, add is as a listener to the element&nbsp; for (const handler of handlers) {&nbsp; &nbsp; btn.addEventListener('click', handler);&nbsp; }});function handler1(event) {&nbsp; console.log('handler 1 says: ' + event.target.textContent);}function handler2(event) {&nbsp; console.log('handler 2 says: ' + event.target.tagName);}function handler3(event) {&nbsp; 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() {&nbsp; const btn = document.getElementById('example-button');&nbsp; for (const checkbox of document.querySelectorAll('input[type=checkbox][id^=handler]')) {&nbsp; &nbsp; checkbox.addEventListener('change', function() {&nbsp; &nbsp; &nbsp; const handler = window[this.id.replace('toggle', '')];&nbsp; &nbsp; &nbsp; btn[`${this.checked ? 'add' : 'remove'}EventListener`]('click', handler);&nbsp; &nbsp; })&nbsp; }});function handler1(event) {&nbsp; console.log('handler 1 says: ' + event.target.textContent);}function handler2(event) {&nbsp; console.log('handler 2 says: ' + event.target.tagName);}function handler3(event) {&nbsp; 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>

狐的传说

您也可以使用 Jquery 并执行以下操作:$("#examle-button").on("click", function(){&nbsp; &nbsp; myfunctionone();&nbsp; &nbsp; myfunctiontwo();&nbsp; &nbsp; myfunctionthree();})
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答