简体   繁体   English

如何组合多个onclick动作?

[英]How to combine multiple onclick actions?

I have two sliders on a page, each with their own pagination, is there a way to combine these two onclick actions, so I have a global one which controls both sliders?我在一个页面上有两个滑块,每个滑块都有自己的分页,有没有办法组合这两个onclick操作,所以我有一个控制两个滑块的全局滑块?

<a href="#" onClick="(function(){slider_image.goToSlide(<?php echo $slide++; ?>);return false;})();return false;">

<a href="#" onClick="(function(){slider_copy.goToSlide(<?php echo $slide++; ?>);return false;})();return false;">

You can't add a single event listener to multiple elements (with vanilla js), but you can consolidate your code a bit using a loop and addEventListener (rather than embedding onclick handlers in your html).您不能将单个事件侦听器添加到多个元素(使用 vanilla js),但是您可以使用循环和addEventListener (而不是在您的 html 中嵌入onclick处理程序)来稍微整合您的代码。 You could also attach the event listener elsewhere in the DOM hierarchy and catch the event as it bubbles up, but hard to know if that would work well in your situation without seeing more of the html.您还可以将事件侦听器附加到 DOM 层次结构中的其他位置,并在事件冒泡时捕获该事件,但是如果不查看更多 html,则很难知道这是否适用于您的情况。 Example using a loop and addEventListener :使用循环和addEventListener示例:

const links = document.querySelectorAll('a');
for (const link of links) {
  link.addEventListener('click', (event) => {
    // your click function here
  });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM