在Twitter Bootstrap Popover中使用jQuery选择元素

5

我将以下内容放置在 Twitter Bootstrap 弹出框中,其中包含一个链接,我想要监听点击事件:

<div id="popover-content">
  <a id="link" href="#">click</a>
</div>

我正在使用一个按钮来显示包含上述内容的弹出窗口:
<button id="trigger" data-placement="bottom" title="title">Reveal popover</button>

我会将按钮与弹出窗口关联起来,并使用jQuery的 click() 函数,以监听弹出窗口中链接的点击事件:

$(function(){
  $('#trigger').popover({ 
    html: true,
    content: function() {
      return $('#popover-content').html();
    }
  }); 

  $('#link').click(function() {
    alert('beep');
  });
});

然而,在点击按钮以显示弹出窗口,然后再点击链接时,似乎无法按照上述意图检测到点击。由于我对DOM、JavaScript和jQuery的理解相当有限,因此我不确定发生了什么。您如何选择/侦听包含在弹出窗口中的元素的操作?

参考:Bootstrap中的弹出窗口

3个回答

7

在这里您不需要执行事件委托。而是在设置内容时,使用 $('#popover-content') 而非 $('#popover-content').html() 。这样默认情况下将附加所注册的事件,而无需任何委派。

示例

$(function(){
  $('#trigger').popover({ 
    html: true,
    content: function() {
      return $('#popover-content'); //<-- Remove .html()
    }
  }); 

  $('#link').click(function() {
    alert('beep');
  });
});

谢谢。我的实际实现可能还有其他问题,因为当我尝试这个建议时,弹出窗口没有任何内容。我会看看能找到什么,因为我更喜欢这种方法。 - TPoy
如果不是必须的,请勿使用事件委托。如果有任何问题,欢迎随时联系我帮忙解决。 - PSL

3
您可以尝试这个方法:
$(document).on('click', '#link', function(){
    alert('beep');
});

太好了,谢谢伙计。现在我明白了。我可以看到<div>是如何动态添加的,即使它已经包含在HTML中。 - TPoy
你不需要事件委托,只需在分配上下文时删除 .html()。请检查我的答案。在这里绑定到文档根本不必要。 - PSL

0

您可以手动使用弹出窗口:

HTML

<div id="popover-wrapper">
  <button id="trigger" data-placement="bottom" title="title">Reveal popover</button>
  <div class="popover right popup-area popover-pos">
    <div class="popover-content">
      <div id="popover-content">
        <a id="link" href="#">click</a>
      </div>
    </div>
  </div>
</div>

CSS

#popover-wrapper {
  .popover {
    left: auto;
    right: 0;
    width: 250px;
    top: 35px;

    .popover-content {
      // ..
    }
  }

  &.open .popover {
    display: block;
  }
}

js

  $('#trigger').hover(function() {
    $(this).stop(true, true).delay(250).queue(function(next){
      $(this).addClass('open');
      next();
    });
  }, function() {
      $(this).stop(true, true).delay(250).queue(function(next){
        $(this).removeClass('open');
        next();
      });
    }
  );

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接