JS代码在Web编程中会经常用到,且功能强大。以下是我在工作中常常用的JS代码,总结如下:
1、触发事伯提交表单
示例1:
<script language="javascript"> function TJsub() { if(confirm('您确定要提交本表单吗?')) return document.form1.action ="test.php?action=set"; frm1.submit(); else return false; }</script>
<form name="form1" method="post"> <input type="text" name="text1" value="测试文字1"> <input type="text" name="text2" value="测试文字2" onClick="TJsub()> <input type="submit" name="submit1" value="提 交""></form>
2、onchange与onclick的事件触发
onchange大多用在下拉列表的触发事件中,重点在“改变”即触发事件。如页面的跳转等。而onclick强调“点击”,即点击即触发事件,用途广泛。
用法比较简单,就不做示例了。
3、“onblur”当焦点离开文本控件时,触发动作。它常常于自动获得焦点一起使用
4、自动获得焦点
示例4:
<body bgcolor="#FFFFFF" οnlοad="document.form1.text2.focus()"> <form name="form1" method="post"> <input type="text" name="text1" value="测试文字1"> <input type="text" name="text2" value="测试文字2" onClick="TJsub()> <input type="submit" name="submit1" value="提 交""> </form></body>
5、回车移动焦点(οnkeydοwn="if(event.KeyCode == 13)event.KeyCode=9")
示例5:
<form name="form1" method="post"> <input type="text" name="text1" value="测试文字1" οnkeydοwn="if(event.KeyCode == 13)event.KeyCode=9"> <input type="text" name="text2" value="测试文字2" οnkeydοwn="if(event.KeyCode == 13)event.KeyCode=9"> <input type="submit" name="submit1" value="提 交""> </form>
6、锁定文本框(readonly)
示例6:
<form name="form1" method="post"> <input type="text" name="text1" value="测试文字1" readonly> <input type="text" name="text2" value="测试文字2" readonly> <input type="submit" name="submit1" value="提 交""> </form>
7、文本框中自动将小写字母转换大写
示例7:
<form name="form1" method="post"> <input type="text" name="text1" value="sample" style="font-variant:Small-caps" > <input type="text" name="text2" style="font-variant:Small-caps" > <input type="submit" name="submit1" value="提 交""> </form>
8、当脚本将焦点定位到一个文本框后,怎么将光标定位文本框里字符串未尾
示例8:
<SCRIPT> function setCaretAtEnd (field) { if (field.createTextRange) { var r = field.createTextRange(); r.moveStart('character', field.value.length); r.collapse(); r.select(); } } </SCRIPT> <FORM NAME="aForm"> <INPUT TYPE="text" NAME="userName" VALUE="測試文字" ONFOCUS="setCaretAtEnd(this)" > <INPUT TYPE="text" NAME="userAge" VALUE="測試文字" ONFOCUS="setCaretAtEnd(this)" > </FORM>