You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Yajra DataTable中添加read more按钮实现长文本折叠显示

实现Yajra DataTable长文本折叠/展开(Read More)功能的方案

1. 后端DataTable逻辑配置

在你定义的Yajra DataTable服务类中,对需要处理的长文本字段做结构封装,要注意开启字段的HTML渲染权限:

// 在对应DataTable类的editColumn方法中处理长文本字段,示例字段为description
->editColumn('description', function ($row) {
    $maxLength = 50; // 可自定义默认展示的字符长度
    $fullText = e($row->description); // 转义内容防止XSS漏洞
    // 文本长度小于阈值直接返回,不需要折叠按钮
    if (mb_strlen($fullText) <= $maxLength) {
        return $fullText;
    }
    $shortText = mb_substr($fullText, 0, $maxLength) . '...';
    // 返回带标识的DOM结构,方便前端做交互匹配
    return '<div class="text-content">
        <span class="short-text">' . $shortText . '</span>
        <span class="full-text d-none">' . $fullText . '</span>
        <a href="javascript:void(0)" class="read-more-toggle text-primary">Read More</a>
    </div>';
})
// 必须将该字段加入rawColumns,否则HTML代码会被直接转义为文本展示
->rawColumns(['description'])

2. 前端样式补充

如果项目未引入Bootstrap,需要先添加隐藏类的基础样式,也可以自定义按钮的展示效果:

/* 基础隐藏类,已引入Bootstrap可省略 */
.d-none {
    display: none !important;
}
/* 可选:调整按钮和文本的对齐效果 */
.read-more-toggle {
    margin-left: 4px;
    font-size: 0.9em;
    cursor: pointer;
}

3. 前端交互JS实现

要使用事件委托绑定点击事件,适配DataTable分页、搜索后表格重新渲染的场景,避免翻页后按钮失效:

$(document).on('click', '.read-more-toggle', function () {
    const $contentWrap = $(this).closest('.text-content');
    const $shortText = $contentWrap.find('.short-text');
    const $fullText = $contentWrap.find('.full-text');
    
    if ($fullText.hasClass('d-none')) {
        // 展开完整内容
        $shortText.addClass('d-none');
        $fullText.removeClass('d-none');
        $(this).text('Read Less');
    } else {
        // 折叠为短内容
        $shortText.removeClass('d-none');
        $fullText.addClass('d-none');
        $(this).text('Read More');
    }
});

注意事项

  • 建议使用mb_strlen和mb_substr处理字符长度,兼容中文、 emoji等多字节字符,避免截断异常
  • 多个字段需要实现该效果时,可将后端的字段处理逻辑封装为公共方法复用,减少重复代码

内容的提问来源于stack exchange,提问作者Virendra kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 03:45:00