代码之家  ›  专栏  ›  技术社区  ›  mlri

从不同的onclick事件执行相同的javascript函数

  •  0
  • mlri  · 技术社区  · 6 月前

    我有以下javascript代码,当我点击HTML中的“播放”按钮时,它会播放视频。

    如何在不复制JavaScript代码的情况下播放不同的视频(HTML中的多个播放按钮)?

    $('#video-icon').on('click', function(e) {
      e.preventDefault();
      $('.video-popup').css('display', 'flex');
      $('.iframe-src').slideDown();
    });
    
    $('.video-popup').on('click', function(e) {
      var $target = e.target.nodeName;
      var video_src = $(this).find('iframe').attr('src');
      if ($target != 'IFRAME') {
        $('.video-popup').fadeOut();
        $('.iframe-src').slideUp();
        $('.video-popup iframe').attr('src', " ");
        $('.video-popup iframe').attr('src', video_src);
      }
    });
    
    <a class="video-section prelative text-center white" role="button" id="video-icon" aria-hidden="true">
      Play
      <div class="video-popup">
        <div class="video-src">
          <div class="iframe-src">
            <iframe src="the video link" allowfullscreen></iframe>
          </div>
        </div>
      </div>
    </a>
    
    1 回复  |  直到 6 月前
        1
  •  0
  •   Rory McCrossan Hsm Sharique Hasan    6 月前

    要让重复的元素执行您需要使用的相同操作 class 选择器来定位它们,而不是 id 因为后者在DOM中必须是唯一的。

    从那里你可以使用 data 弹出触发器上的属性,用于存储应在弹出窗口中显示的视频位置。您可以在弹出窗口显示时进行设置。

    以下是一个完整的工作示例,其中对您的逻辑进行了一些其他修改:

    const $videoPopup = $('#video-popup');
    const $videoContainer = $videoPopup.find('.iframe-src');
    const $videoIframe = $videoContainer.find('iframe');
    
    $('.video-icon').on('click', function(e) {
      e.preventDefault();
      $videoPopup.css('display', 'flex');
      $videoContainer.slideDown();
      $videoIframe.prop('src', $(this).data('video-url'));
      console.log(`Showing popup for ${$(this).data('video-url')}...`);
    });
    
    $videoPopup.on('click', function(e) {
      var $target = e.target.nodeName;
      if ($target != 'IFRAME') {
        $videoPopup.fadeOut();
        $videoContainer.slideUp();
        $videoIframe.prop('src', '');
      }
    });
    #video-popup {
      display: none;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <a class="video-icon video-section prelative text-center white" role="button" aria-hidden="true" data-video-url="video-1-location.mp4">
      Play video 1
    </a>
    <a class="video-icon video-section prelative text-center white" role="button" aria-hidden="true" data-video-url="video-2-location.mp4">
      Play video 2
    </a>
    
    <div id="video-popup">
      <div class="video-src">
        <div class="iframe-src">
          <iframe src="the video link" allowfullscreen></iframe>
        </div>
      </div>
    </div>