【问题标题】:Selecting an element with jQuery in a Twitter Bootstrap Popover在 Twitter Bootstrap Popover 中使用 jQuery 选择元素
【发布时间】:2014-05-30 10:04:29
【问题描述】:

我将以下内容放在 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 的理解相当有限,所以我不确定这里发生了什么。如何选择/侦听对弹出框中包含的元素的操作?

参考:Popovers in Bootstrap

【问题讨论】:

    标签: javascript jquery twitter-bootstrap


    【解决方案1】:

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

    Demo

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

    【讨论】:

    • 谢谢。我的实际实现肯定有其他事情发生,因为当我尝试这个建议时弹出框不包含任何内容。我会看看我能找到什么,因为我更喜欢这个。
    • 是的,如果不完全需要,不要使用事件委托。让我知道它是否有效?如有任何问题,我们很乐意提供帮助。
    【解决方案2】:

    你可以试试这个:

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

    【讨论】:

    • 宾果游戏。谢了哥们。现在这对我来说很有意义。我可以看到
      是如何动态添加的,即使它已经包含在 HTML 中。
    • 您不需要事件委托,只需在分配上下文时删除 .html() 即可。请检查我的答案。您正在绑定到这里根本不需要的文档。
    【解决方案3】:

    您可以手动使用弹出框:

    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();
          });
        }
      );
    

    【讨论】:

      猜你喜欢
      相关资源
      最近更新 更多
      热门标签