首页 > 解决方案 > Tippy.JS“TypeError:instance.setContent 不是函数”

问题描述

当我尝试在 Tippy.JS 中设置工具提示的内容时,我收到错误消息TypeError: instance.setContent is not a function

这是我的代码:

var instance = tippy('#range', {
    placement: 'bottom',
    content: '',
});

$('#range').on('input', function () {
    instance.setContent('Hello World!');
});

标签: javascriptjquerytippyjs

解决方案


尽管可能很奇怪,但是无论您使用什么类型的选择器,tippy 都会返回一个 ARRAY。那是因为tippy函数可以根据选择器返回多个项目。例如。

tippy("[notice='tippy']",{
            theme:'light',
            allowHTML:true,
            placement: 'bottom',
            content: contentElement.innerHTML,
            animation:'scale-subtle',
            trigger:'click',
            interactive: true,
            maxWidth: "none",
            allowHTML:true,
            onShow(instance) {
                instance.setContent(contentElement.innerHTML);
                this.windowHeight = window.innerHeight;
            }
        })

上面的代码选择了所有具有属性 notice 的元素,其值为 'tippy' 并返回一个 Tippy 实例数组

[{/*Tippy Object*/},{/*Tippy Object*/}] //Javascript Array of Objects

如果您确定只返回一个元素,我建议您使用 [0] 仅返回数组中的那个元素。

let oneTippy = tippy("#tippyElement",{
            theme:'light',
            allowHTML:true,
            placement: 'bottom',
            content: contentElement.innerHTML,
            animation:'scale-subtle',
            trigger:'click',
            interactive: true,
            maxWidth: "none",
            allowHTML:true,
            onShow(instance) {
                instance.setContent(contentElement.innerHTML);
                this.windowHeight = window.innerHeight;
            }
        })[0]

推荐阅读