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

使用jQuery截断Razor视图中Html.DisplayFor文本无效,无控制台错误

jQuery实现Razor视图文本截断无效问题

我在Razor视图中用Html.DisplayFor展示绑定的BlogContent字符串,想通过jQuery实现文本截断功能,用了一段截断代码后却没效果,浏览器控制台也没报错。虽然能用C#的SubString方法实现,但我更倾向于用jQuery完成。

我的csHtml代码如下:

@{ 
    Layout = null;
}

<div class="blog-post-body">
    <p class="p-bottom-20">@Html.DisplayFor(modelItem => item.BlogContent)</p>
</div>

@section scripts
{
<script src="~/js/jquery.min.js"></script>
<script src="~/bootstrap/js/bootstrap.min.js"></script>

<script>
    $(document).ready(function () {
        $('ul.pagination > li.disabled > a').addClass('page-link');
        truncateText(".p-bottom-20", 100);
    });

    function truncateText(selector, maxLength) {
        $(selector).text((i, txt) => txt.length > maxLength ? txt.substr(0, maxLength) + "..." : txt);
    };
</script>
}

问题排查与解决办法

1. 确认元素是否被正确选中

页面加载完成后,可能目标元素还没渲染出来(比如异步加载场景),或者选择器写错了。可以在代码里加个判断,确认元素存在:

$(document).ready(function () {
    $('ul.pagination > li.disabled > a').addClass('page-link');
    // 检查元素数量
    console.log("目标元素数量:", $(".p-bottom-20").length);
    if ($(".p-bottom-20").length > 0) {
        truncateText(".p-bottom-20", 100);
    }
});

2. 替换为更可靠的遍历写法

原代码用text()的回调写法理论上没问题,但换成each()遍历能更直观地排查每个元素的情况:

function truncateText(selector, maxLength) {
    $(selector).each(function() {
        var originalText = $(this).text();
        if (originalText.length > maxLength) {
            $(this).text(originalText.substr(0, maxLength) + "...");
        }
    });
}

3. 处理含HTML标签的内容

如果BlogContent包含HTML标签,直接用text()获取纯文本截断会丢失原格式,这时可以用以下方法保留HTML结构:

function truncateHtmlText(selector, maxLength) {
    $(selector).each(function() {
        var $el = $(this);
        var plainText = $el.text();
        if (plainText.length > maxLength) {
            var truncated = plainText.substr(0, maxLength) + "...";
            // 替换原内容中的纯文本部分,保留HTML标签
            $el.html($el.html().replace(plainText, truncated));
        }
    });
}

4. 确认脚本加载顺序

确保jQuery在自定义脚本之前加载,否则会因为$未定义导致代码不执行(虽然你控制台没报错,但还是要确认)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 14:40:32