首页 > 解决方案 > 如何选择多个具有相同名称的类并触发相同的功能?

问题描述

如何使此功能选择所有类“.stop”以及当我们单击具有该类的元素时停止视频?

window.addEventListener("load", function(event) {
    window.addEventListener('scroll', checkScroll, false);
    window.addEventListener('resize', checkScroll, false);

    let playvideo = document.querySelector('video');

    let close = document.querySelector('.stop');


    close.onclick = () => {
        playvideo.pause();
    }
});

标签: javascriptfunctionclass

解决方案


代表

const container = document.getElementById('videoContainer'); // or whatever you have
container.addEventListener('click',e => {
  const tgt = e.target;
  if (tgt.classList.contains('stop')) {
    tgt.closest('div').querySelector('video').pause(); // assuming the stop is in the same div
  }
})

推荐阅读