Javascript : Destroy tippy. js实例

标签 javascript php jquery twitter-bootstrap tippyjs

我有以下代码显示包含动态数据的工具提示。 它工作正常,但它为所有人显示相同的工具提示。

我已经使用了 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/

相关文章:

javascript - onmouseover方法动态分配

javascript - 如何在服务器端查看用户认证状态

javascript - react 更新问题

php - 如何编写一个 PHP + MySQL 的 web 服务来执行每秒 1000 个请求(INSERT 和 SELECT)

javascript - 来自 ajax 的模型绑定(bind),用于将日期值传递为 null

php - 当我使用 jQgrid 单击同一行中的链接时,我需要从 jqGrid 获取整行数据

javascript - 上传前删除图片预览

javascript - 如何检查 session 存储中是否存在项目?

php - Laravel 在嵌套中间件组中排除路由

php - 在 Laravel 中执行迁移的向上和向下方法时运行特定代码