JQuery

1个成员

很实用的二款jquery 截取字符串长度方法

发表于 2017-02-15 3319 次查看
jquery 可以用text()方法来取得字符串,再用length 判断长度,然后用substring()方法格式化截断后加'...'省略号。
 代码如下 复制代码
<!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'>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=gb2312' />
<title>cookie</title>
<script src='/jquery/jquery-1.3.2.min.js' type='text/javascript'></script>
<style>
*{ margin:0; padding:0;font-family:'宋体',Arial, Helvetica, sans-serif;}
#best{ width:300px; height:200px; border:1px solid #ccc; margin:60px auto 0; line-height:1.6; font-size:14px; padding:10px 0 0 10px}
.blank{ font-size:18px; font-weight:bold; text-align:center; padding:20px}
</style>
<script type='text/javascript'>
jQuery.fn.limit=function(){
var self = $('div[limit]');
self.each(function(){
var objString = $(this).text();
var objLength = $(this).text().length;
var num = $(this).attr('limit');
if(objLength > num){
$(this).attr('title',objString);
objString = $(this).text(objString.substring(0,num) + '...');
}
})
}
$(function(){
$(document.body).limit();
})
</script>
</head>
<body>
<div class='blank'>请按F5刷新页面。。。。</div>
<div id='best'>
<div limit='12'>字符串字符串字符串字符串字符串字符串字符串字符串字符串</div>
<div limit='10'>字符串字符串字符串字符串字符串字符串字符串</div>
<div limit='12'>字符串字符串字符串字符串字符串</div>
<div limit='12'>字符串字符串字符串字符串字符串字符串字符串字符串</div>
<div limit='10'>字符串字符串字符串字符串字符串字符串字符串</div>
</div>
</body>
</html>

完整实例代码二

 代码如下 复制代码

<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>cookie</title>
<script src="http://img.jb51.net/jslib/jquery/jquery-1.3.2.min.js" type="text/javascript"></script>
<style>
*{ margin:0; padding:0;font-family:"宋体",Arial, Helvetica, sans-serif;}
#best{ width:300px; height:200px; border:1px solid #ccc; margin:60px auto 0; line-height:1.6; font-size:14px; padding:10px 0 0 10px}
.blank{ font-size:18px; font-weight:bold; text-align:center; padding:20px}
</style>
<script type="text/javascript">
jQuery.fn.limit=function(){
    var self = $("div[limit]");
    self.each(function(){
        var objString = $(this).text();
        var objLength = $(this).text().length;
        var num = $(this).attr("limit");
        if(objLength > num){
$(this).attr("title",objString);
            objString = $(this).text(objString.substring(0,num) + "...");
        }
    })
}
$(function(){
    $(document.body).limit();
})
</script>
</head>
<body>
    <div class="blank">请按F5刷新页面。。。。</div>
<div id="best">
    <div limit="12">计算字串的长度长度长度长度</div>
    <div limit="10">这边有优化很公开这边</div>
    <div limit="12">这边有优化很公开长度长度很公开长度</div>
    <div limit="12">计算字长度长度</div>
    <div limit="10">这边有优化很边有优化很边有优化很边有优化很边有优化很</div>
</div>
</body>
</html>

发表回复
你还没有登录,请先登录注册