如何将 Twitter Bootstrap 工具提示绑定到动态创建的元素? [英] How do I bind Twitter Bootstrap tooltips to dynamically created elements?

查看:31
本文介绍了如何将 Twitter Bootstrap 工具提示绑定到动态创建的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 Twitter 引导工具提示与 javascript 结合使用,如下所示:

I'm using Twitter bootstrap tooltips with javascript like the following:

$('a[rel=tooltip]').tooltip();

我的标记如下所示:

<a rel="tooltip" title="Not implemented" class="btn"><i class="icon-file"></i></a>

这很好用,但我动态添加了 元素并且工具提示没有显示这些动态元素.我知道这是因为我只在文档完成加载时绑定 .tooltip() 一次,具有典型的 jquery $(document).ready(function() 功能.

This works fine, but I add <a> elements dynamically and the tooltips aren't showing up for those dynamic elements. I know it's because I only bind .tooltip() once when the document is finished loaded with the typical jquery $(document).ready(function() functionality.

如何将其绑定到动态创建的元素?通常我会通过 jquery live() 方法来做到这一点.但是,我用来绑定的事件是什么?我只是不确定如何将引导程序 .tooltip() 与 jquery .live() 连接起来.

How can I bind this to dynamically created elements? Usually I would do this via the jquery live() method. However, what is the event that I use to bind? I'm just not sure how to hook up the bootstrap .tooltip() with jquery .live().

我找到了一种方法来完成这项工作:

I've found one way to make this work is something like this:

/* Add new 'rows' when plus sign is clicked */
$("a.add").live('click', function () {
    var clicked_li = $(this).parent('li');
    var clone = clicked_li.clone();

    clone.find(':input').each(function() {
        $(this).val('');
    });

    clicked_li.after(clone);
    $('a[rel=tooltip]').tooltip();
});

这有效,但似乎有点骇人听闻.我还在 $(ready) 调用中调用完全相同的 .tooltip() 行.那么,页面第一次加载并匹配该选择器时存在的元素是否会以工具提示结束两次?

This works, but seems kind of hackish. I'm also calling the exact same .tooltip() line in the $(ready) call. So, do the elements that exist when the page first loads and match that selector end up with the tooltip twice?

我认为这种方法没有任何问题.我只是在寻找最佳实践或对行为的理解.

I don't see any problems with this approach. I'm just looking for a best practice or understanding of the behavior.

推荐答案

试试这个:

$('body').tooltip({
    selector: '[rel=tooltip]'
});

这篇关于如何将 Twitter Bootstrap 工具提示绑定到动态创建的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆