我找不到这个问题的解决方案plugin因为我无法通过 Ajax 找到任何有效的演示或外部内容文档。
基本上我有一个简单的 div
,带有鼠标悬停 JS 功能:
<div onmouseover="myFunct(this,'.$comment['id'].');" >Hover Me</div>
这是我的 JS 函数:
function myFunct(element, id){
$(element).tooltipster({
contentCloning: true,
interactive:true,
maxWidth:250,
contentAsHTML:true,
content: 'Loading...',
// 'instance' is basically the tooltip. More details in the "Object-oriented Tooltipster" section.
functionBefore: function(instance, helper) {
var $origin = $(helper.origin);
// we set a variable so the data is only loaded once via Ajax, not every time the tooltip opens
if ($origin.data('loaded') !== true) {
$.ajax({
type: "POST",
url: baseUrl+"/requests/load_profilecard.php",
data: 'id='+id+"&token_id="+token_id,
cache: false,
success: function(html) {
// call the 'content' method to update the content of our tooltip with the returned data
instance.content(html);
// to remember that the data has been loaded
$origin.html('loaded', true);
}
});
}
}
});
}
为什么工具提示仅在第二次鼠标悬停时显示?
这是一个类似的示例。 JSFiddle
更新
感谢支持,这解决了我的问题:
<div class="tooltip" data-id="'.$comment['id'].'">Hover me!</div>
<script type="text/javascript">
$(document).ready(function() {
$('.tooltip').tooltipster({
content: 'Loading...',
functionBefore: function(instance, helper){
var $origin = $(helper.origin);
$.ajax({
type: "POST",
url: baseUrl+"/requests/load_profilecard.php",
data: 'id='+ $origin.attr('data-id')+"&token_id="+token_id,
cache: false,
success: function(html) {
// call the 'content' method to update the content of our tooltip with the returned data
instance.content(html);
}
});
},
interactive:true,
contentAsHTML:true,
maxWidth:250
});
});
</script>
无论如何,这不适用于 Ajax 动态内容,我不知道为什么(我尝试将其插入到 Ajax 页面上,没办法)
最佳答案
我建议一些事情:首先,将 JS 与 HTML 分开(这被认为是最佳实践),其次,在页面加载时初始化 Tooltipster,最后,删除包装函数。初始化工具提示后,您的代码将在悬停时默认触发。
将 JS 与 HTML 分开
<div class="hover-me tool-tip" data-commentId="12345">Hover Me</div>
文档就绪时初始化 Tooltipster
$(document).ready(function() {
$('.tooltip').tooltipster();
});
通过悬停触发工具提示
$('.hover-me').tooltipster({
// all of your code from above
functionBefore: function(){
var commentId = $(this).attr('data-commentId');
}
});
注意:
Tooltipster 的默认触发器是 hover
(如文档中所示),但是,您可以通过传入 trigger:hover
来显式设置它,这将使您的代码更具可读性,因此更易于维护。
Tooltipster 支持建议(如 comments 中所示)
我添加这个是因为它强化了我上面的解决方案,并为 future 的开发人员添加了上下文......,并且它可能在评论部分中被忽略。
You initialize your tooltip when the mouseover event has already been fired, so Tooltipster cannot "hear" this first event and open the tooltip. You'd better initialize your tooltips at page load and put your comment id in a data-id attribute that you'll retrieve in functionBefore when you prepare your ajax call.
关于javascript - 为什么这个 jQuery 插件(Tooltipster)的 Ajax 内容只有在鼠标悬停 2 次后才显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38793656/