当前位置: 首页 > 图文教程 > 网络编程 > Javascript > 用JS剩余字数计算的代码

Javascript
Add a Table to a Word Document
Add Formatted Text to a Word Document
用jscript实现新建word文档
用jscript实现新建和保存一个word文档
Open and Print a Word Document
Use Word to Search for Files
Convert Seconds To Hours
Sample script that deletes a SQL Server database
Sample script that displays all of the users in a given SQL Server DB
firefox中用javascript实现鼠标位置的定位
div+css实现鼠标放上去,背景跟图片都会变化。
Locate a File Using a File Open Dialog Box
Save a File Using a File Save Dialog Box
用jscript实现列出安装的软件列表
List the Stored Procedures in a SQL Server database
Display SQL Server Login Mode
Display SQL Server Version Information
List all the Databases on a SQL Server
用jscript启动sqlserver
Stop SQL Server

Javascript 中的 用JS剩余字数计算的代码


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-12   浏览: 191 ::
收藏到网摘: n/a

函数中首先给maxChars变量指定了值(输入区内最多可用的字符数,注意,该变量是个可用于计算的数值) 先看看HTML代码:
<textarea name="description" onkeyup="checkLength(this);"></textarea>
<br /><small>文字最大长度: 250. 还剩: <span id="chLeft">250</span>.</small>
可以看出onkeyup是当用户离开键盘后触发的事件,传递的参数是this(也就是当前所在的文档区域)
然后结合JS代码看一下:
<script type="text/javascript">
function checkLength(which) {
var maxChars = 250;
if (which.value.length > maxChars)
which.value = which.value.substring(0,maxChars);
var curr = maxChars - which.value.length;
document.getElementById("chLeft").innerHTML = curr.toString();
}
</script>
函数中首先给maxChars变量指定了值(输入区内最多可用的字符数,注意,该变量是个可用于计算的数值)
然后从参数中得到在textarea中已输入的字符长度,并与前面指定的最大长度做比较。
当输入的字符长度超过范围,则使用substring来强制限制其长度(0,maxChars)的意思就是可输入范围是0个字符到maxChars(变量)个字符。
var curr = maxChars - which.value.length;的作用是算出还可用多少个字符,将数值保存在curr中。
最后通过getElementById定位到id为chLeft的对象(在该HTML中为span),并将curr里的值通过toString方法把数值变为字符串,反馈到span标签内。