首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >有没有办法在jQuery中截断元素的文本?

有没有办法在jQuery中截断元素的文本?
EN

Stack Overflow用户
提问于 2014-10-04 01:42:39
回答 5查看 2K关注 0票数 0

我有这样的元素:

代码语言:javascript
复制
"<span class=interests><a href=>Acoustics</a><a href=>Actuarial Studies</a><a href=>Administrative Law</a></span>" 

我想通过a的文本截断它,例如:上面例子中的Acoustics。如果它大于50,我想截断它。

我怎样才能用jQuery做到这一点?

EN

回答 5

Stack Overflow用户

发布于 2014-10-04 01:49:11

尝尝这个

代码语言:javascript
复制
    <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
EN

Stack Overflow用户

发布于 2014-10-04 02:42:27

代码语言:javascript
复制
$('.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

票数 1
EN

Stack Overflow用户

发布于 2014-10-04 01:47:13

尝试以下操作:

代码语言:javascript
复制
$('span a').each(function(){
    if($(this).text().length > 50)
        $(this).text($(this).text().substr(0,50));
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26183979

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档