服务端DataTable的render函数中Tippy tooltip无法显示问题排查
问题描述
使用Blade构建文章列表页面时,服务端模式的DataTable中,render函数里的Tippy tooltip无法正常工作——控制台没有报错,但鼠标悬停在描述(body)列的tooltip元素上时,完全看不到提示框。
Blade代码:
<x-layout> <h3>List posts</h3> <table id="example" class="display" style="width:100%"> <thead> <tr> <th>ID</th> <th>TITLE</th> <th>DESCRIPTION</th> <th>PUBLISH</th> </tr> </thead> </table> <script src="https://unpkg.com/@popperjs/core@2"></script> <script src="https://unpkg.com/tippy.js@6"></script> <script> new DataTable('#example', { ajax: "{{ route('retrieveposts') }}", processing: true, serverSide: true, columns: [{ data: 'id', name: 'id' }, { data: 'title', name: 'title', render: function(data, type, row) { return ` <strong id="title_${row.id}" class="title"> ${data} </strong> `; } }, { data: 'body', name: 'body', render: function(data, type, row) { return ` <div data-tippy-content="Tooltip"> <span id="value_description_${row.id}"> ${data}</span> </div> `; } }, { data: 'is_publish', name: 'is_publish', render: function(data, type, row) { return ` <span> ${data} </span> `; } }, ] }); tippy('[data-tippy-content]') </script> </x-layout>
问题原因
你开启了DataTable的服务端模式(serverSide: true),表格内容是通过AJAX异步请求后动态渲染到DOM中的。而你在DataTable初始化完成后直接调用tippy('[data-tippy-content]')——此时表格的动态内容还没加载出来,Tippy找不到这些后续生成的元素,自然无法完成绑定。
解决方案
方法1:监听DataTable的draw事件
每次DataTable完成渲染(包括加载数据、分页、排序、搜索后),重新初始化Tippy,确保动态生成的元素能被绑定:
new DataTable('#example', { ajax: "{{ route('retrieveposts') }}", processing: true, serverSide: true, columns: [ // 原有列配置保持不变 ], // 添加draw回调函数 drawCallback: function() { // 先销毁已存在的Tippy实例,避免重复绑定导致异常 tippy('[data-tippy-content]', { destroy: true }); // 重新初始化Tippy tippy('[data-tippy-content]'); } });
方法2:使用Tippy的委托模式(更推荐)
直接把Tippy绑定到表格这个父元素上,通过委托机制自动识别后续动态生成的tooltip目标元素,无需每次渲染都重新初始化:
// 正常初始化DataTable new DataTable('#example', { ajax: "{{ route('retrieveposts') }}", processing: true, serverSide: true, columns: [ // 原有列配置保持不变 ] }); // 用委托模式初始化Tippy tippy('#example', { target: '[data-tippy-content]', // 从目标元素的data属性中获取tooltip内容 content(reference) { return reference.getAttribute('data-tippy-content'); } });
内容的提问来源于stack exchange,提问作者ghost_of_the_code
相关产品推荐
相关产品推荐

