2013-04-29 238 views
0

我試圖設置一個事件,在我的元素打開後觸發。所以我有一個工具提示,我有一個顯示工具提示的點擊事件。那麼當發生這種情況時,我會設置一個文檔點擊事件,因此如果用戶點擊舞臺上的任何位置,它將刪除所有工具提示。但是,在工具提示甚至有機會展示之前它會被調用。所以它一遍又一遍地發射文檔事件。.on事件不斷被解僱一次又一次

$('.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'); 
    }; 
+0

在腳本中稍後將函數聲明爲變量看起來有點奇怪嗎? – adeneo 2013-04-29 19:52:23

回答

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

DEMO: http://jsfiddle.net/dirtyd77/uPHk6/8/


附註: 我建議從on去除.tooltip功能如

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