2014-10-03 58 views
0

我有这样的元素:有没有办法在jQuery中截断元素的文本?

"<span class=interests><a href=>Acoustics</a><a href=>Actuarial Studies</a><a href=>Administrative Law</a></span>" 

我想通过一个文本e.g截断这一点:在上面的例子声学。如果它超过50,我想截断它。

我该怎么用jQuery做到这一点?

+2

做一个省略号插件的谷歌搜索。 – Barmar 2014-10-03 17:45:49

+0

Trivially:'e.text(e.text()。substr(0,50))' - 但您可能对更复杂的方法感兴趣。 – user2864740 2014-10-03 17:46:57

+0

[只使用CSS?](https://developer.mozilla.org/en-US/docs/Web/CSS/text-overflow) – 2014-10-03 17:46:59

回答

0

尝试以下操作:

$('span a').each(function(){ 
    if($(this).text().length > 50) 
     $(this).text($(this).text().substr(0,50)); 
}); 
+0

这适用于所有锚文本修剪。我想要的是找到所有锚点文本中的字符数,然后截断它们。 – snnlaynnkrdsm 2014-10-03 18:00:28

+0

编辑,但我不知道你想要做什么 – nicolas 2014-10-03 18:11:39

+0

ABCDEF如果ABCDEF.length> 3让我们说它会看起来像这样:ABC ... – snnlaynnkrdsm 2014-10-03 18:17:05

1

试试这个

<span id="mainText" > 
<a> 
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</a></span> 
    <script> 
     jQuery(document).ready(function(){ 
     $('span a').each(function(a, v){ 
      if ($(this).text().length>50){ 
       $(this).remove(); 
      } 
     }) 


}) 
</script> 
+0

他不想将其全部删除,只是将其截断为50个字符。 – Barmar 2014-10-03 17:52:50

+0

对不起,我更改代码使用此代码 – 2014-10-03 17:59:10

1
$('.interests a').each(function(){ 
    var truncated = $(this).text().substr(0, 50); 
    //Updating with ellipsis if the string was truncated 
    $(this).text(truncated+(truncated.length<50?'':'[...]')); 
}); 

demo

0

传递函数的文字方法会让你改变动态文本

$('a').text(function(index, value) { 
    if (value.length > 50){ 
    return value.substr(0, 50); 
    } 
}); 
0

ABCDEF如果ABCDEF.length> 3,您说,可以看出这样的:ABC ... - real1 42分钟前

<span class='interests'> 
    <a href='#'>Acoustics</a> 
    <a href='#'>Actuarial Studies</a> 
    <a href='#'>Administrative Law</a> 
    <a href='#'>Something inside your head, Something inside your head, Something inside your head, Something inside your head</a> 
</span> 

然后:

var total = 0; 
var truncated = ""; 

$('.interests a').each(function(){ 
    total+=$(this).text().length; 
    truncated+=$(this).text(); 
}); 

if(total>50){ 
    truncated = truncated.substring(0, 50)+'...'; 
    $('.interests').html(truncated);  
} 

你得到:

AcousticsActuarial StudiesAdministrative LawSometh... 

丢弃的联系?

http://jsfiddle.net/abrhmcc/x8pkorjn/7/

相关问题