jquery限制文本长度 [英] jquery limit text by length

查看:121
本文介绍了jquery限制文本长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



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



任何其他方式也会感激。


解决方案

这将隐藏文本的一部分

 <!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/xhtmlxml:lang =enlang =en>
< head>
< meta http-equiv =Content-Typecontent =text / html; charset = utf-8/>

< title> untitled< / title>
< style type =text / cssmedia =screen>
.hide {
display:none;
}
< / style> ;,
< script src =js / jquery-1.3.2.min.jstype =text / javascriptcharset =utf-8>< / script&
< script type =text / javascriptcharset =utf-8>
$(function(){
var $ elem = $('p'); //具有要隐藏文本的元素
var $ limit = 10; //数字的字符显示
var $ str = $ elem.html(); //获取文本
var $ strtemp = $ str.substr(0,$ limit); //获取可见部分字符串
$ str = $ strtemp +'< span class =hide>'+ $ str.substr($ limit,$ str.length)+'< / span>'; // Recompose具有跨度标记的字符串包围其隐藏部分
$ elem.html($ str); //将字符串写入DOM
})
< / script>

< / head>
< body>
< p>一些长度字符串到这里< / p>
< / body>
< / html>


Can i hide text in a DIV after a number of characters with jQuery?

So far I think it would go something like this - jQuery would cycle through the text until it gets to a certain number of characters. It would then wrap a DIV from that position to the end of the text which could then be hidden with the hide() method. I'm not sure how to insert that wrapping text.

Any other way around this would also be appreciated.

Thanks.

解决方案

This will hide a part of the text

<!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>

这篇关于jquery限制文本长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆