2016-09-02 35 views
0

我分页用户的内部,在我看来字符我有:使用SUBSTR限制元素

<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; 
} 

回答

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("..."); 
      }) 
     } 
    }); 
}); 
+0

奇怪的是,这是导致3个字符的长度,我想0-2代替0-200。 '30 ...'和''[I ...'和'I l ...' –

+0

_“奇怪的是,这导致了3个字符的长度”_你可以创建stacksnippets或jsfiddle来演示吗? – guest271314

+0

它在jfiddle中工作,当我发表我的第一条评论时,我将代码从200更改为20,然后测试了不同的数字......每次它在文本开始之前就好像有14个隐形字符一样工作。必须是'user.profile' –