2013-08-18 13 views
1

我试图剪切过长的文本并将其替换为“...”。jquery的问题 - 用“...”替换太长的文本

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/

+0

请问你能解释一下你想要什么,你的问题是什么。 – Sergio

+0

请给你的问题一个有意义的标题:-) – herrjeh42

+0

可能与http://stackoverflow.com/questions/12371329/html-select-dropdrown-width-is-too-big重复 – herrjeh42

回答

1

我想你只需要改变这一行

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

这个

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

R.

2

为什么不直接使用CSS?

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

Demo

+0

看来他希望它在选择下拉菜单中,因此CSS选项不起作用。如在http://jsfiddle.net/9sQKM/1/中 –

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)) + '... '); 
    } 
});