使用substr来限制元素内的字符

时间:2016-09-02 06:53:23

标签: jquery substring

我正在对用户进行分页,在我看来,我有:

<li class="profile">
  <%= user.profile %> 
</li>

我想将li.profile限制为200个字符,然后是三个点'...'

以下不起作用:

$(document).ready(function(){
   $("li.profile").each(function(){
       if ($(this).html().length > 200) {
           $(this).html($(this).html().substr(0, 200)); 
            $(this).append('...');
        }
    });
});

from developer tools

这是它在开发人员工具中的样子。

css

li.profile {
font-size: 14px;
padding-bottom: 5px;
text-align: left;
padding-left: 5px;
}

1 个答案:

答案 0 :(得分:0)

使用.text(); .html()设置了.innerHTML元素,而不是.textContent

$(document).ready(function(){
   $("li.profile").each(function(){
       if (this.textContent.length > 200) {
           $(this).text(function(_, text) {
             return text.substr(0, 200).concat("..."); 
           })
        }
    });
});