使用jQuery截断字符串文本

ttp71kqs  于 9个月前  发布在  jQuery
关注(0)|答案(1)|浏览(77)

我有一个Razor视图Html.DisplayFor,我在其中显示一些文本。现在我想使用jQuery截断文本。我使用的jQuery代码来自jQuery Truncate
在我的csHtml中,我有如下内容,BlogContent是我绑定的一些字符串。当然,我认为我可以在C#中对BlogContent进行SubString等截断。但是我想用jQuery。我试过下面的代码,但没有运气。

@{ 
    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>
    
            <!-- Bootstrap -->
            <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>
    
    }

我在浏览器控制台上没有看到任何与此相关的错误。

plicqrtu

plicqrtu1#

如果你使用的是Layout = null;,那么@section Scripts就不起作用,因为这个部分是在_Layout.cshtml中定义的。你必须在视图中添加一个完整的html文档。

@{
    Layout = null;
}

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>title</title>
  </head>
  <body>
    <div class="blog-post-body">
      <p class="p-bottom-20">@Html.DisplayFor(modelItem => item.BlogContent)</p>
    </div>

    <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>
  </body>
</html>

相关问题