Change Twitter Bootstrap Tooltip content on click

2019-01-05 08:42发布

I have a tooltip on an anchor element, that sends an AJAX request on click. This element has a tooltip (from Twitter Bootstrap). I want the tooltip content to change when the AJAX request returns successfully. How can I manipulate the tooltip after initiation?

23条回答
Root(大扎)
2楼-- · 2019-01-05 08:45

The following worked the best for me, basically I'm scrapping any existing tooltip and not bothering to show the new tooltip. If calling show on the tooltip like in other answers, it pops up even if the cursor isn't hovering above it.

The reason I went for this solution is that the other solutions, re-using the existing tooltip, led to some strange issues with the tooltip sometimes not showing when hovering the cursor above the element.

function updateTooltip(element, tooltip) {
    if (element.data('tooltip') != null) {
        element.tooltip('hide');
        element.removeData('tooltip');
    }
    element.tooltip({
        title: tooltip
    });
}
查看更多
【Aperson】
3楼-- · 2019-01-05 08:45

I'm using this easy way out:

$(document).ready(function() {
    $("#btn").prop('title', 'Click to copy your shorturl');
});

function myFunction(){
  $(btn).tooltip('hide');
  $(btn).attr('data-original-title', 'Test');
  $(btn).tooltip('show');
});

查看更多
Explosion°爆炸
4楼-- · 2019-01-05 08:47

You can set content on tooltip call with a function

        $("#myelement").tooltip({
            "title": function() {
                return "<h2>"+$("#tooltipcontainer").html()+"</h2>";
            }
        });

You don't have to use only the title of the called element.

查看更多
叛逆
5楼-- · 2019-01-05 08:47

Destroy any pre-existing tooltip so we can repopulate with new tooltip content

$(element).tooltip("destroy");    
$(element).tooltip({
    title: message
});
查看更多
一纸荒年 Trace。
6楼-- · 2019-01-05 08:48

With Tooltip object Boostrap :

$(element).attr('data-original-title', 'New value');
$(element).data('bs.tooltip').tip().find('.tooltip-inner').text('New value');
查看更多
啃猪蹄的小仙女
7楼-- · 2019-01-05 08:49

In bootstrap 4 I just use $(el).tooltip('dispose'); then recreate as normal. So you can put the dispose before a function that creates a tooltip to be sure it doesn't double up.

Having to check the state and tinker with values seems less friendly.

查看更多
登录 后发表回答