How to add and show a Bootstrap tooltip inside a j

2019-09-06 14:10发布

I am trying to add and display a Bootstrap 3 tooltip from within a click function in jQuery.

It works well when I'm using an anonymous function for the click handler, but if I try to place the code into a named function I get the error TypeError: undefined is not a function (evaluating '$button.tooltip(...

The contents of the JS file is below. This is loaded after both jQuery and bootstrap.min.js.

$(function() {
    function confirmClick(event) {
        event.preventDefault();

        $button = event.target;
        console.log($button);

        $button.tooltip({
            title: 'Are you sure?',
            trigger: 'manual',
        }).tooltip('show');

        $button.unbind('click');
    }

    $('.btn-confirm').click(confirmClick);
})

Ultimately, I'm looking to use setTimeout to re-add the click handler and hide the tooltip after X seconds.

The end behavior will be the user clicking on the button, a tooltip appearing asking "Are you sure?" and if they click again before X seconds the link is followed. If not, the tooltip is hidden and the same action is prepared for the next click.

I've also tried adding the tooltip using wither a manual or click trigger and then manipulating it from within the confirmClick() function, but any attempt to hit .tooltip from within a named click function seems to fail.

1条回答
闹够了就滚
2楼-- · 2019-09-06 14:40

You need to wrap your target with jQuery selector to use .tooltip().

Do $button = $(event.target); instead of $button = event.target;.

Prepend your variable with $ if, and only if, your variable stores a jQuery object.

查看更多
登录 后发表回答