表单的常用事件
1、focus:获取焦点,获取焦点是触发
2、blur:失去焦点,失去焦点时触发
3、change:检测数据发生变化,并失去焦点时触发
4、input :数据发生变化是触发
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<form>
<P>
<label for="user-id">用户id:</label>
<input type="text" id="user-id" name="user-id">
</P>
<p>
<label for="level">级别</label>
<select id="level" name="level">
<option value="1">初级</option>
<option value="2">中级</option>
<option value="3" selected>高级</option>
</select>
</p>
</form>
<script>
var input = document.getElementById('user-id');
//focus 获取焦点
input.addEventListener('focus',function (ev) {
ev.target.style.backgroundColor = 'pink';
},false);
//blur 失去焦点
input.addEventListener('blur',function (ev) {
return ev.target.value.length === 0 ? alert("ID不能为空") : false;
},false);
// input 数据发生变化时触发,不必失去焦点
input.addEventListener('input',function (ev) {
console.log(ev.target.value);
},false);
//change 数据发生改变,并且失去焦点时,才会触发
input.addEventListener('change',function (ev) {
console.log(ev.target.value);
},false);
var select = document.getElementById('level');
</script>
</body>
</html>

浙公网安备 33010602011771号