JS中表單中的幾個常見的事件
(1)OnClick事件:滑鼠單擊事件。
例項:建一個JSP檔案,程式碼如下:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script type="text/javascript">
function check(){
alert("你好");
}
</script>
</head>
<body>
<input type='button' value="點我" onclick
</body>
</html>
效果:點選”點我“按鈕,就會出現”你好“。
(2)OnSubmit事件:表單中的確定按鈕被點選時發生的事件。
案例解析:彈出表單中提交的內容
例項:建一個JSP,程式碼如下:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form name="testform
你的姓名是:?<br />
<input type="text" name="fname" />
<input type="submit" value="提交" />
</form>
<script type="text/javascript">
var form = document.getElementById('form');
form.onsubmit
alert('Hello ' + testform.fname.value +'!');
}
</script>
</body>
</html>
(3)onblur:在物件失去焦點時發生的事件。
案例解析:我們將在使用者離開輸入框時執行 JavaScript 程式碼(輸入內容之後在空白處點選一下即可)
例項:<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<p>請輸入你的英文名字: <input type="text" id="fname"></p>
<p>請輸入你的年齡: <input type="text" id="age"></p>
<script type="text/javascript">
function upperCase(){
var x=document.getElementById("fname").value;
document.getElementById("fname").value=x.toUpperCase();
}
var fname = document.getElementById('fname');
var age = document.getElementById('age');
fname.onblur = function (){
upperCase();
}
age.onblur = function (){
alert('age is ' + this.value);
}
</script>
</body>
</html>
(4)
onfoucs:在物件獲得焦點時發生的事件,案例如下
案例解析:當輸入框獲得焦點時,其背景顏色將改變,
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<!--onfoucs事件-->
<p>第一個:<input type="text" onfocus="setStyle(this.id)" id="fname-foucs"></p>
<p>第二個:<input type="text" onfocus="setStyle(this.id)" id="lname-foucs"></p>
<script type="text/javascript">
function setStyle(x) {
document.getElementById(x).style.background = "yellow";
}
</script>
</body>
</html>
(5)
onchange:在物件的值發生改變時觸發的事件,案例如下
案例解析:當輸入框的value值發生改變時將其轉換為大寫
<!--onchange事件-->
<p>輸入您的姓名:<input type="text" id="fname-change" onchange="upperCase(this.id)" /></p>
<script type="text/javascript">
function upperCase(x) {
var y = document.getElementById(x).value;
document.getElementById(x).value = y.toUpperCase();
}
</script>
(6)onload事件:在頁面或者圖片載入完成以後執行的程式碼,案例如下:
<script type="text/javascript">
window.onload = function(){
alert('頁面載入已完成,會執行之後的程式碼');
}
</script>