为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

摇曳的蔷薇 2021-11-25 16:08:35
我确实明白这是一种突兀的方式,但我正在实施的方式已经走了很长一段路,所以我现在无法真正改变,我使用的方法有时有效,其他方法只作用于最后的点击操作,我想要一种模式它可以正常工作,请在代码之前参考以查看我如何添加 onclick 操作。我想知道为什么它有时有效,而在其他时候却无法全部执行<button onclick="myfunctionone(); myfunctiontwo(); myfunctionthree();">click here</button>
查看完整描述

2 回答

?
白猪掌柜的

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>



查看完整回答
反对 回复 2021-11-25
?
狐的传说

TA贡献1804条经验 获得超3个赞

您也可以使用 Jquery 并执行以下操作:


$("#examle-button").on("click", function(){

    myfunctionone();

    myfunctiontwo();

    myfunctionthree();

})


查看完整回答
反对 回复 2021-11-25
  • 2 回答
  • 0 关注
  • 236 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信