2014-10-03 81 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/

相關問題