JQuery获取文本框中字符长度的代码

jquery 可以用text()方法来取得字符串,再用length 判断长度,然后用substring()方法格式化截断。
 看下例子吧 
JS 方法: 
复制代码代码如下:
<script type="text/javascript"> 
// 得到字符串的真实长度(双字节换算为两个单字节) 
function getStrActualLen(sChars) 

//sChars.replace(/[^\x00-\xff]/g,"xx").length/1024+"字节"; 
//Math.round(sChars.replace(/[^\x00-\xff]/g,"xx").length/1024);这个貌似不好使 
return alert(formatNum(sChars.replace(/[^\x00-\xff]/g,"xx").length/1024,4)); 
}  // www.jbxue.com
//格式化小数,并四舍五入。如:formatNum(100.12345678,4) 
function formatNum(Num1,Num2){ 
if(isNaN(Num1)||isNaN(Num2)){ 
return(0); 
}else{ 
Num1=Num1.toString(); 
Num2=parseInt(Num2); 
if(Num1.indexOf('.')==-1){ 
return(Num1); 
}else{ 
var b=Num1.substring(0,Num1.indexOf('.')+Num2+1); 
var c=Num1.substring(Num1.indexOf('.')+Num2+1,Num1.indexOf('.')+Num2+2); 
if(c==""){ 
return(b); 
}else{ 
if(parseInt(c)<5){ 
return(b); 
}else{ 
return((Math.round(parseFloat(b)*Math.pow(10,Num2))+Math.round(parseFloat(Math.pow(0.1,Num2).toString().substring(0,Math.pow(0.1,Num2).toString().indexOf('.')+Num2+1))*Math.pow(10,Num2)))/Math.pow(10,Num2)); 






Jquery方法: 
复制代码代码如下:

function getStrActualLen(){ 
var count=$("#sChars").val().length/1024; 
return Math.round(count*Math.pow(10,4)); 


jquery 截取字符串长度 
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 - www.jbxue.com</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> 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值