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>