How do I bind Twitter Bootstrap tooltips to dynamically created elements?

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

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

My markup looks like this:

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

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.

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

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]'
});

If you have multiple tooltip configurations that you want to initialise, this works well for me.

$("body").tooltip({
    selector: '[data-toggle="tooltip"]'
});

You can then set the property on individual elements using data attributes.


For me, only catching the mouseenter event was a bit buggy, and the tooltip was not showing/hiding properly. I had to write this, and it is now working perfectly:

$(document).on('mouseenter','[rel=tooltip]', function(){
    $(this).tooltip('show');
});

$(document).on('mouseleave','[rel=tooltip]', function(){
    $(this).tooltip('hide');
});
链接地址: http://www.djcxy.com/p/42494.html

上一篇: 在页面上加载高级jQuery版本

下一篇: 如何将Twitter Bootstrap工具提示绑定到动态创建的元素?