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

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

问题描述

我正在使用带有JavaScript的Twitter引导工具提示,如下所示:

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>

这很好,但是我动态添加了<a>元素,而那些动态元素的工具提示没有出现.我知道这是因为在完成典型的jquery $(document).ready(function()功能的文档加载后,我只绑定一次.tooltip().

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()方法来做到这一点.但是,我用来绑定的事件是什么?我只是不确定如何将bootstrap .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天全站免登陆