jquery按长度限制文本

我可以使用jQuery在一些字符后隐藏DIV中的文本吗?

到目前为止,我认为它会像这样 – jQuery会循环遍历文本,直到达到一定数量的字符。 然后它会将DIV从该位置包装到文本的末尾,然后可以使用hide()方法隐藏它。 我不知道如何插入包装文本。

任何其他方式也将受到赞赏。

谢谢。

这将隐藏文本的一部分

    untitled      

Some lenghty string goes here

我认为目的可以比上面解释的更容易解决

 $(function(){ $(".title").each(function(i){ len=$(this).text().length; if(len>10) { $(this).text($(this).text().substr(0,10)+'...'); } }); }); 

上面的jquery代码将隐藏div文本(如果超过10个字符)以及广告……最后会解释还有更多内容。

Jeff我有同样的问题想要将文本限制器添加到动态内容中,所以这是我的解决方案:

 // TEXT CHARACTER LIMITER $(document).ready(function() { $.fn.textlimit = function() { return this.each(function() { var $elem = $(this); // Adding this allows u to apply this anywhere var $limit = 22; // The number of characters to show var $str = $elem.html(); // Getting the text var $strtemp = $str.substr(0,$limit); // Get the visible part of the string $str = $strtemp + '' + $str.substr($limit,$str.length) + ' ...'; $elem.html($str); }) }; }); // Call the text limiter above $(document).ready(function() { $('.someGenericClass .anotherClass').textlimit() }); 

我用这个替换原来的答案…..

        
Here are all
my characters.
I would like to limit them to 20.
 $.fn.textlimit = function(limit) { return this.each(function(index,val) { var $elem = $(this); var $limit = limit; var $strLngth = $(val).text().length; // Getting the text if($strLngth > $limit) { $($elem).text($($elem).text().substr( 0, $limit )+ "..."); } }) }; **how to use** $("#DivId").textlimit(60); 

如果在body标签上放置onkeydown事件处理程序,则可以计算感兴趣的div中的长度,然后在完成后隐藏它,并删除事件处理程序。