0

I'm trying to setup an event where it fires after my element is opened. So I have a tooltip and I have a click event which shows the tooltip. Then when that happens I setup a document click event that gets fired so if the user clicks anywhere on the stage it removes all tooltips. But what's happening is it gets called before the tooltip even gets a chance to show. So it's firing the document event over and over again.

 $('.container img').popover({placement:'top', trigger:'manual', animation:true})
    .click(function(evt){
        evt.preventDefault();
        el = $(this);

        if(el.hasClass('active')){
            el.popover('hide');

        }else{
            clearDocumentEvent();
            el.popover('show');

                $(document).on('click.tooltip touchstart.tooltip', ':not(.container img)', function(){
                    hideAllTooltips();

                });

        }

        el.toggleClass('active');
    })

    var hideAllTooltips = function(){
        $('.container img').popover('hide');
        $('.container img').removeClass('active');
    }

    var clearDocumentEvent = function(){
        $(document).off('click.tooltip touchstart.tooltip');
    };
4

1 回答 1

1

问题源于事件冒泡。您可以通过执行以下测试来验证这一点:

$(document).on('click.tooltip touchstart.tooltip', ':not(.container img)', function(){
    //hideAllTooltips();
    console.log($(this)); // will return .container, body, html
});

尝试使用event.stopPropogation()

$(document).on('click.tooltip touchstart.tooltip', ':not(.container img)', function(e){
     e.stopPropagation();
     hideAllTooltips();
});

演示:http: //jsfiddle.net/dirtyd77/uPHk6/8/


旁注:我建议.tooltipon功能中删除,例如

$(document).on('click touchstart', ':not(.container img)', function(){
    e.stopPropagation();
    hideAllTooltips();
});
于 2013-04-29T20:22:38.983 回答