我有这个元素:
"<span class=interests><a href=>Acoustics</a><a href=>Actuarial Studies</a><a href=>Administrative Law</a></span>"
我想通过一个文本截断它,例如:上面例子中的声学。如果它超过50,我想截断它。
我怎么能用jQuery做到这一点?
答案 0 :(得分: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>
答案 1 :(得分: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?'':'[...]'));
});
答案 2 :(得分:0)
尝试以下方法:
$('span a').each(function(){
if($(this).text().length > 50)
$(this).text($(this).text().substr(0,50));
});
答案 3 :(得分:0)
将函数传递给text方法可以动态更改文本
$('a').text(function( index, value ) {
if (value.length > 50){
return value.substr(0, 50);
}
});
答案 4 :(得分:0)
ABCDEF如果ABCDEF.length&gt; 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...
丢弃链接?