【问题标题】:Problems with jquery - replace a too long text with "..."jquery 的问题 - 用“...”替换太长的文本
【发布时间】:2013-08-20 10:55:01
【问题描述】:

我尝试剪切过长的文本并用“...”替换它。

HTML:

<div class="test">    
    <span>Item text goes in here but it is way too long to fit inside a select option that has a fixed width adding more</span>
</div>

jquery:

$.each($('.test span'), function(key, testName) {
    var curText = $(testName).text();
    $(this).attr('title', curText);
    var lengthToShortenTo = Math.round(parseInt($(this).parent('.test').css('width'), 10) / 7.3);

    if (curText.length > lengthToShortenTo) {
        $(this).text(curText.substring((curText.length - lengthToShortenTo), curText.length) + '... ');
    }
});

缩短跨度的输出为:

选择具有固定宽度的选项添加更多...

但我想获取文本的第一部分而不是最后一部分。所以这也是我想要的:

项目文本在此处输入,但太长了...

演示:http://jsfiddle.net/jNWS6/247/

【问题讨论】:

  • 请您更好地解释您想要什么以及您的问题是什么。
  • 请给你的问题一个有意义的标题:-)
  • 好吧,我希望现在好多了:-)

标签: jquery


【解决方案1】:

你拿错了子串的一部分,你应该拿第一部分

$.each($('.sedcardHolder span'), function(key, sedcardName) {
    var curText = $(sedcardName).text();
    $(this).attr('title', curText);

    var lengthToShortenTo =     Math.round(parseInt($(this).parent('.sedcardHolder').css('width'), 10) / 5.3);

    if (curText.length > lengthToShortenTo) {
        $(this).text(curText.substring(0,(curText.length - lengthToShortenTo)) + '... ');
    }
});

【讨论】:

    【解决方案2】:

    我想你只需要改变这一行

    $(this).text(curText.substring((curText.length - lengthToShortenTo), curText.length) + '... ');
    

    到这里

    $(this).text(curText.substring(0, lengthToShortenTo) + '... ');
    

    R.

    【讨论】:

      【解决方案3】:

      为什么不直接使用 CSS?

      .test {
          white-space:nowrap;
          overflow:hidden;
          text-overflow:ellipsis;
      }
      

      Demo

      【讨论】:

      • 看来他希望它在一个选择下拉列表中,因此 CSS 选项不起作用。如jsfiddle.net/9sQKM/1
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-03
      • 1970-01-01
      • 2011-02-14
      • 1970-01-01
      • 2023-01-10
      • 2019-02-11
      相关资源
      最近更新 更多