jquery按长度限制文本

use*_*est 10 css formatting jquery text

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

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

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

谢谢.

Swa*_*esh 21

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

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

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


小智 10

这将隐藏文本的一部分

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

    <title>untitled</title>
    <style type="text/css" media="screen">
        .hide{
            display: none;
        }
    </style>
    <script src="js/jquery-1.3.2.min.js" type="text/javascript" charset="utf-8"></script>
    <script type="text/javascript" charset="utf-8">
        $(function(){
            var $elem = $('p');         // The element or elements with the text to hide
            var $limit = 10;        // 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 + '<span class="hide">' + $str.substr($limit,$str.length) + '</span>';  // Recompose the string with the span tag wrapped around the hidden part of it
            $elem.html($str);       // Write the string to the DOM 
        })
    </script>

</head>
<body>
<p>Some lenghty string goes here</p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)