jquery – 弹出窗口内容中的Bootstrap切换按钮不起作用

我做了一个 jsFiddle,我使用twitter bootstrap切换按钮&酥料饼.

HTML:

<div class="btn-group btn-toggle">
  <button class="btn btn-sm btn-info">On</button>
  <button class="btn btn-sm btn-primary active">Off</button>
</div>

<button id="popbutton" class="btn btn-lg btn-warn">pop up</button>

JS:

var popupElement = '<div class="btn-group btn-toggle"><button class="btn btn-sm btn-  info">On</button><button class="btn btn-sm btn-primary active">Off</button></div>';

$('#popbutton').popover({
  animation: true,content: popupElement,html: true
});


$('.btn-toggle').click(function () {
   $(this).find('.btn').toggleClass('active');

   if ($(this).find('.btn-primary').size() > 0) {
      $(this).find('.btn').toggleClass('btn-primary');
   }
   if ($(this).find('.btn-danger').size() > 0) {
      $(this).find('.btn').toggleClass('btn-danger');
   }
   if ($(this).find('.btn-success').size() > 0) {
      $(this).find('.btn').toggleClass('btn-success');
   }
   if ($(this).find('.btn-info').size() > 0) {
      $(this).find('.btn').toggleClass('btn-info');
   }

  $(this).find('.btn').toggleClass('btn-default');

});

切换按钮有效,但是当我在弹出框中使用相同的按钮时,它将无法工作.

请建议一种方法.

解决方法

由于加载时不存在弹出按钮,因此需要使用事件委派.而不是size()(从jQuery 1.8开始不推荐使用),你应该使用length属性
$('body').on('click','.btn-toggle',function () {
    $(this).find('.btn').toggleClass('active');

    if ($(this).find('.btn-primary').length > 0) {
        $(this).find('.btn').toggleClass('btn-primary');
    }
    if ($(this).find('.btn-danger').length > 0) {
        $(this).find('.btn').toggleClass('btn-danger');
    }
    if ($(this).find('.btn-success').length > 0) {
        $(this).find('.btn').toggleClass('btn-success');
    }
    if ($(this).find('.btn-info').length > 0) {
        $(this).find('.btn').toggleClass('btn-info');
    }

    $(this).find('.btn').toggleClass('btn-default');
});

Updated fiddle

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: &lt;span id=&quot...
jQuery 添加水印 &lt;script src=&quot;../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...