【问题标题】:button click event not working in Jquery按钮单击事件在 Jquery 中不起作用
【发布时间】:2018-08-09 13:26:06
【问题描述】:

我正在使用模式查询将 div 附加到正文,并且按钮与模式相关联。我正在尝试使用按钮关闭模式,我的代码如下。它看起来像是事件触发的问题。

 $('a.launch-youtube-modal').click(function(event) {
      event.preventDefault();
      $('body').append([
        '<div class="youtube-modal">',
          '<div class="youtube-modal-container"><div class="youtube-modal-video-container">',
         '<iframe width="671" height="495" src="'+ $(this).attr('href') +'" frameborder="0" allowfullscreen id="youtube-video"></iframe>',
         '<button class="ss-icon ss-gizmo youtube-close">close</button>',
          '</div></div>',
        '</div>'
      ].join(''));

 function closeYoutubeModal() {
        if (!video) return;
        video.jQYT('destroy');
        $('.youtube-modal').remove();
      }
      $('.youtube-modal .youtube-close').click(function () {
         closeYoutubeModal();    
      });
    });

【问题讨论】:

标签: javascript jquery events event-handling bootstrap-modal


【解决方案1】:

试试这个:使用.on 为动态创建的元素绑定点击事件处理程序。您可以将关闭按钮单击处理程序保留在模态单击处理程序之外

$('a.launch-youtube-modal').click(function(event) {
      event.preventDefault();
      $('body').append([
        '<div class="youtube-modal">',
          '<div class="youtube-modal-container"><div class="youtube-modal-video-container">',
         '<iframe width="671" height="495" src="'+ $(this).attr('href') +'" frameborder="0" allowfullscreen id="youtube-video"></iframe>',
         '<button class="ss-icon ss-gizmo youtube-close">close</button>',
          '</div></div>',
        '</div>'
      ].join(''));

 });

function closeYoutubeModal() {
   if (!video) return;
   video.jQYT('destroy');
   $('.youtube-modal').remove();
}
$(document).on('click','.youtube-modal .youtube-close',function () {
    closeYoutubeModal();    
});

【讨论】:

    【解决方案2】:

    工作:

    $('a.launch-youtube-modal').click(function(event) {
          event.preventDefault();
          $('body').append([
            '<div class="youtube-modal">',
              '<div class="youtube-modal-container"><div class="youtube-modal-video-container">',
             '<iframe width="671" height="495" src="'+ $(this).attr('href') +'" frameborder="0" allowfullscreen id="youtube-video"></iframe>',
             '<button class="ss-icon ss-gizmo youtube-close">close</button>',
              '</div></div>',
            '</div>'
          ].join(''));
    
     });
    
     $('body').on('click','.youtube-close', function() {
            console.log("Youtube modal closed");
            $('.youtube-modal').remove();
          });
        });
    

    【讨论】:

      猜你喜欢
      • 2018-09-18
      • 2013-06-01
      • 2017-12-04
      • 2014-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多