我有以下代码显示包含动态数据的工具提示。 它工作正常,但它为所有人显示相同的工具提示。
我已经使用了 tip._tippy.destroy();
位没有工作。
<div id="template" style="display: none;">
Loading a tooltip...
</div>
上面显示工具提示的元素:
<span class="more-tags otherPostTags" data-postId="{{$post->id}}">...</span>
Js:
const template = document.querySelector('#template')
const initialText = template.textContent
const tip = tippy('.otherPostTags', {
animation: 'shift-toward',
arrow: true,
html: '#template',
onShow() {
const content = this.querySelector('.tippy-content')
if (tip.loading || content.innerHTML !== initialText) return
tip.loading = true
node = document.querySelectorAll('[data-tippy]');
let id = node[0].dataset.postid;
$.ajax({
url: '/get/post/'+id+'/tags',
type: 'GET',
success: function(res){
let preparedMarkup = '';
res.tags.map(function(item) {
preparedMarkup +=
'<span class="orange-tag" style="background-color: '+item.color+'">'+
item.name +
'</span>';
});
content.innerHTML = preparedMarkup;
tip.loading = false
},
});
},
onHidden() {
const content = this.querySelector('.tippy-content');
content.innerHTML = initialText;
},
});
当我悬停时,tooptip 显示来自数据库的标签,但它在悬停时显示相同的标签/数据,数据不同但它显示工具提示,这是第一次悬停时出现。
最佳答案
你的问题在这里:
node = document.querySelectorAll('[data-tippy]');
let id = node[0].dataset.postid;
您始终选择相同的元素 (node[0]
),而不是选择当前悬停的元素。
您可以使用回调函数参数来点击当前元素(onShow
第一个参数包含对引用原始元素的对象的引用,在我的示例中 - tip。引用
)。示例如下:
tippy.setDefaults({
arrow: true,
delay: 240,
theme: 'my-tippy',
onShow(tip) {
console.log('Post id: ' + $(tip.reference).data('postid'));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://unpkg.com/tippy.js@3/dist/tippy.all.min.js"></script>
<button data-tippy="Tooltip" data-postId="1">Post 1</button>
<button data-tippy="Another tooltip" data-postId="2">Post 2</button>
<button data-tippy="Another tooltip" data-postId="3">Post 3</button>
关于Javascript : Destroy tippy. js实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52393097/