How to add and show a Bootstrap tooltip inside a jQuery click function?

纵然是瞬间 提交于 2019-12-12 03:08:20

问题


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:


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.



来源:https://stackoverflow.com/questions/29405583/how-to-add-and-show-a-bootstrap-tooltip-inside-a-jquery-click-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!