2016-07-07 45 views
0

在下面的代碼中,我點擊按鈕後打開p元素的工具提示,如果再次單擊該按鈕,關閉工具提示。防止jQuery工具提示在mouseleave上關閉動態添加的類

$(document).ready(function() { 
 
    var obj = null; 
 

 
    $('input').click(function() { 
 
    if (obj == null) { 
 
     obj = $('p'); 
 
     obj.tooltip({ 
 
     items: 'p', 
 
     content: 'Some help' 
 
     }); 
 
     obj.tooltip("open"); 
 
    } else { 
 
     obj.tooltip('disable'); 
 
     obj = null; 
 
    } 
 
    }); 
 

 
    $('.help').mouseenter(function(e) { 
 
    e.stopImmediatePropagation(); 
 
    }); 
 

 
    $('.help').mouseleave(function(e) { 
 
    e.stopImmediatePropagation(); 
 
    }); 
 
});
<link href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet" /> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script> 
 

 
<input type='button' value='Click me' /> 
 

 
<p class='help'> 
 
    Some text 
 
</p>

我想現在要做的是,除了我是點擊按鈕時我動態添加類的「幫助」到p元素同樣的事情。工具提示沒有保持打開狀態,而是在鼠標懸停時消失。我觀察到mouseenter()/mouseleave()處理程序沒有開火,所以我用on()替換了它們。現在事件發生,但工具提示仍然關閉。

$(document).ready(function() { 
 
    var obj = null; 
 

 
    $('input').click(function() { 
 
    if (obj == null) { 
 
     obj = $('p'); 
 
     obj.tooltip({ 
 
     items: 'p', 
 
     content: 'Some help' 
 
     }); 
 
     obj.tooltip("open"); 
 
     obj.addClass('help'); // Added statically in DOM in above snippet 
 
    } else { 
 
     obj.tooltip('disable'); 
 
     obj = null; 
 
    } 
 
    }); 
 

 
    $(document.body).on('mouseenter', '.help', function(e) { 
 
    //console.log('on mouseenter'); 
 
    e.stopImmediatePropagation(); 
 
    }); 
 

 
    $(document.body).on('mouseleave', '.help', function(e) { 
 
    //console.log('on mouseleave'); 
 
    e.stopImmediatePropagation(); 
 
    }); 
 

 
});
<link href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet" /> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script> 
 
    
 
<input type = 'button' value = 'Click me' /> 
 

 
<p> 
 
Some text 
 
</p>

回答

0

的提示似乎移動從Some text離開後,一旦mouseleave事件觸發被隱藏。除非您需要使用鼠標移除功能,否則您可以從工具提示中完全禁用此事件,以達到您想要的效果。

obj.tooltip("open"); 
obj.toggleClass("help"); // Toggle help class 
obj.off("mouseleave"); // Remove the event from the tooltip 

的jsfiddle:https://jsfiddle.net/c1f0ft8j/