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" onload="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、斷行符號移動焦點(onkeydown="if(event.KeyCode == 13)event.KeyCode=9")
樣本5:
<form name="form1" method="post">
<input type="text" name="text1" value="測試文字1" onkeydown="if(event.KeyCode == 13)event.KeyCode=9">
<input type="text" name="text2" value="測試文字2" onkeydown="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>
暫時就這些........