【问题标题】:Bootstrap popover doesn't trigger on elements just added to the DOMBootstrap 弹出框不会在刚刚添加到 DOM 的元素上触发
【发布时间】:2013-01-30 07:07:00
【问题描述】:

当我将鼠标悬停在 div 上时,我正在显示一个图标。

点击那个图标,我想显示一个弹出框。

由于某种原因,弹出框根本没有触发。

我的 HTML:

<div class="kpi">
    <p>this is the kpi</p>
</div>

我的 JavaScript:

$('.kpi').live('mouseenter', function(e) {
        $(this).find('p:first').append('<span class="gear" style="margin-left: 10px; position: absolute;"><i class="icon-cog"></i></span>');
    });

    $('.kpi').live('mouseleave', function(e) {
        $('.gear').remove();
    });

    $('.gear').popover({
        title:"titke",
        content:"click me",
        trigger:"click"
    });

$('.gear').live('click', function(e) {
    alert('clicked the gear');    
});

我可能会犯什么菜鸟错误?

这里是fiddle

【问题讨论】:

  • 您使用的是哪个 jquery 版本? .live() 已弃用并从 1.9 中删除,请改用 .on()
  • 它在小提琴中使用 1.7 并且在那里不起作用。

标签: javascript css twitter-bootstrap popover


【解决方案1】:

popover 在不存在的元素上初始化。

$('.kpi').live('mouseenter', function(e) {
    $(this).find('p:first').append('<span class="gear" style="margin-left: 10px; position: absolute;"><i class="icon-cog"></i></span>');

    //Call the popover after creation of gear
    $('.gear').popover({
        title:"titke",
        content:"click me",
        trigger:"click"
    });

});

    $('.kpi').live('mouseleave', function(e) {
        $('.gear').remove();
    });


$('.gear').live('click', function(e) {
    alert('clicked the gear');    
});

演示:Fiddle

你需要在.gear元素被创建并附加到dom之后调用$('.gear').popover({...})$(this).find('p:first').append(...)之后)

【讨论】:

  • Bootstrap 包含在小提琴中。
  • bootstrap.css 被包括在内,而不是 bootstrap.js 不是
  • 抱歉错过了,你的popover() 定义还是放错了地方
【解决方案2】:

首先,您的 JSFiddle 缺少 jQuery popover 插件:我假设您想要包含 this one

但真正的问题是这行代码:

$(this).find('p:first').append('<span class="gear" ....

悬停.kpi 时,您正在动态创建具有特定类的跨度。 .popover 的初始化已经执行,并且不再为此类执行。我们需要再次将它应用于新创建的元素,如下所示:

var span = $('<span class="gear" style="margin-left: 10px; position: absolute;"><i class="icon-cog"></i></span>');

span.popover({
    title: "title",
    content: "click me",
    trigger: "click"
});

$(this).find('p:first').append(span);

虽然它可能不是您想要的(因为您应用了第二个“click”句柄),但我认为您可以从这里获取它。

JSFiddle proof.

【讨论】:

  • 非常感谢.. 同时我发现了与您指出的相同的事情。
猜你喜欢
  • 2013-04-13
  • 2012-11-06
  • 2011-05-22
  • 2011-01-27
  • 2018-02-03
  • 1970-01-01
  • 1970-01-01
  • 2017-10-17
  • 2011-09-05
相关资源
最近更新 更多