Appearance
第6章:jQuery 事件处理(交互核心,必学)
6.1 事件绑定的两种方式(基础+推荐)
方式1:简单绑定(如click()、mouseover(),适合简单场景)
- 作用:直接绑定事件到元素上
- 语法:
$(selector).eventName(function() {}) - 示例:javascript
// 绑定点击事件 $('#btn').click(function() { alert('按钮被点击了'); }); // 绑定鼠标移入事件 $('#element').mouseover(function() { $(this).css('background-color', 'yellow'); });
方式2:on() 绑定(推荐,支持多事件、事件委托,灵活强大)
作用:更灵活的事件绑定方式,支持多事件绑定和事件委托
语法:
- 绑定单个事件:
$(selector).on('event', function() {}) - 绑定多个事件:
$(selector).on('event1 event2', function() {}) - 事件委托:
$(parent).on('event', 'childSelector', function() {})
- 绑定单个事件:
示例:
javascript// 绑定单个事件 $('#btn').on('click', function() { alert('按钮被点击了'); }); // 绑定多个事件 $('#element').on('mouseenter mouseleave', function() { $(this).toggleClass('highlight'); }); // 事件委托 $('#list').on('click', '.item', function() { $(this).css('color', 'red'); });
6.2 常用鼠标事件(高频使用)
click():点击事件
- 作用:当元素被点击时触发
- 示例:javascript
$('#btn').click(function() { console.log('按钮被点击'); });
mouseover()/mouseout():鼠标移入/移出事件
- 作用:当鼠标移入/移出元素时触发
- 示例:javascript
$('#element').mouseover(function() { $(this).css('background-color', 'yellow'); }).mouseout(function() { $(this).css('background-color', 'white'); });
mouseenter()/mouseleave():鼠标进入/离开事件(与over/out区别)
作用:当鼠标进入/离开元素时触发,不会冒泡到子元素
区别:
mouseover/mouseout:会冒泡到子元素mouseenter/mouseleave:不会冒泡到子元素,性能更好
示例:
javascript$('#element').mouseenter(function() { $(this).css('background-color', 'yellow'); }).mouseleave(function() { $(this).css('background-color', 'white'); });
6.3 常用键盘事件(表单交互常用)
keydown()/keyup():键盘按下/松开事件
- 作用:当键盘按键按下/松开时触发
- 示例:javascript
$('#input').keydown(function(event) { console.log('按键按下:', event.key); }).keyup(function(event) { console.log('按键松开:', event.key); });
keypress():键盘按下并松开事件
- 作用:当键盘按键按下并松开时触发
- 示例:javascript
$('#input').keypress(function(event) { console.log('按键按下并松开:', event.key); });
6.4 表单事件(表单交互核心)
focus()/blur():表单元素获取/失去焦点
- 作用:当表单元素获取/失去焦点时触发
- 示例:javascript
$('#input').focus(function() { $(this).css('border-color', 'blue'); }).blur(function() { $(this).css('border-color', 'gray'); });
change():表单元素值改变事件(如select、input)
- 作用:当表单元素的值改变时触发
- 示例:javascript
$('#select').change(function() { console.log('选择值:', $(this).val()); }); $('#input').change(function() { console.log('输入值:', $(this).val()); });
submit():表单提交事件(阻止默认提交行为)
- 作用:当表单提交时触发
- 示例:javascript
$('form').submit(function(event) { // 阻止默认提交行为 event.preventDefault(); // 表单验证 const username = $('#username').val(); if (!username) { alert('请输入用户名'); return false; } // 手动提交表单 console.log('表单提交'); });
6.5 事件解绑(off() 方法,移除已绑定的事件)
off():移除已绑定的事件
作用:移除元素上已绑定的事件
语法:
- 移除所有事件:
$(selector).off() - 移除指定事件:
$(selector).off('event') - 移除指定事件和处理函数:
$(selector).off('event', handler)
- 移除所有事件:
示例:
javascript// 绑定点击事件 function handleClick() { console.log('按钮被点击'); } $('#btn').on('click', handleClick); // 移除点击事件 $('#btn').off('click', handleClick); // 移除所有事件 $('#btn').off();
6.6 事件委托(on() 实现,解决动态元素事件绑定问题)
什么是事件委托?
- 事件委托是将事件绑定到父元素上,利用事件冒泡原理来处理子元素的事件
- 适用于动态生成的元素,无需为每个元素单独绑定事件
实现方式:
javascript
// 事件委托,为所有.list-item元素绑定点击事件
$('#list').on('click', '.list-item', function() {
$(this).css('color', 'red');
});
// 动态添加元素
$('#addBtn').click(function() {
$('#list').append('<div class="list-item">新项</div>');
});事件委托的优势:
- 减少事件绑定数量,提高性能
- 支持动态生成的元素
- 代码更简洁
6.7 事件对象(event,获取事件相关信息:鼠标位置、键盘按键等)
事件对象的常用属性和方法:
- event.target:触发事件的元素
- event.currentTarget:绑定事件的元素
- event.type:事件类型
- event.pageX/event.pageY:鼠标位置
- event.key:键盘按键
- event.preventDefault():阻止默认行为
- event.stopPropagation():阻止事件冒泡
示例:
javascript
$('#btn').click(function(event) {
console.log('事件类型:', event.type);
console.log('触发元素:', event.target);
console.log('绑定元素:', event.currentTarget);
});
$('#element').mousemove(function(event) {
console.log('鼠标位置:', event.pageX, event.pageY);
});
$('#link').click(function(event) {
// 阻止默认行为(阻止链接跳转)
event.preventDefault();
console.log('链接被点击,但不会跳转');
});6.8 实操案例:实现按钮点击、表单交互、动态元素事件绑定
案例:事件处理练习
HTML结构:
html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery事件处理练习</title>
<style>
.container {
width: 400px;
margin: 20px auto;
padding: 20px;
border: 1px solid #ccc;
}
.box {
width: 100px;
height: 100px;
background-color: #f0f0f0;
margin: 20px 0;
text-align: center;
line-height: 100px;
cursor: pointer;
}
.highlight {
background-color: yellow;
}
input {
padding: 5px;
margin: 10px 0;
width: 100%;
}
button {
padding: 5px 10px;
margin: 5px;
cursor: pointer;
}
.list {
margin: 20px 0;
}
.list-item {
padding: 10px;
border: 1px solid #ddd;
margin: 5px 0;
}
</style>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div class="container">
<h2>事件处理练习</h2>
<!-- 鼠标事件 -->
<div class="box" id="mouseBox">鼠标事件</div>
<!-- 键盘事件 -->
<input type="text" id="keyInput" placeholder="输入文本">
<div id="keyInfo"></div>
<!-- 表单事件 -->
<form id="myForm">
<input type="text" id="username" placeholder="用户名">
<input type="password" id="password" placeholder="密码">
<button type="submit">提交</button>
</form>
<!-- 动态元素 -->
<div>
<button id="addItem">添加项目</button>
<div class="list" id="itemList">
<div class="list-item">项目1</div>
<div class="list-item">项目2</div>
</div>
</div>
<!-- 事件解绑 -->
<div>
<button id="bindBtn">绑定点击事件</button>
<button id="unbindBtn">解绑点击事件</button>
<div id="bindBox">点击我</div>
</div>
</div>
<script>
$(document).ready(function() {
// 鼠标事件
$('#mouseBox')
.mouseenter(function() {
$(this).addClass('highlight').text('鼠标进入');
})
.mouseleave(function() {
$(this).removeClass('highlight').text('鼠标离开');
})
.click(function() {
$(this).css('background-color', 'red').text('被点击了');
setTimeout(() => {
$(this).css('background-color', '#f0f0f0').text('鼠标事件');
}, 1000);
});
// 键盘事件
$('#keyInput').keyup(function(event) {
$('#keyInfo').text('输入内容:' + $(this).val() + ',按键:' + event.key);
});
// 表单事件
$('#myForm').submit(function(event) {
event.preventDefault();
const username = $('#username').val();
const password = $('#password').val();
if (!username || !password) {
alert('请填写用户名和密码');
return false;
}
alert('表单提交成功!用户名:' + username);
});
// 动态元素事件委托
$('#itemList').on('click', '.list-item', function() {
$(this).css('color', 'red').text($(this).text() + ' (已点击)');
});
// 添加动态元素
$('#addItem').click(function() {
const itemCount = $('#itemList .list-item').length + 1;
$('#itemList').append('<div class="list-item">项目' + itemCount + '</div>');
});
// 事件绑定与解绑
function handleClick() {
alert('绑定的点击事件被触发');
}
$('#bindBtn').click(function() {
$('#bindBox').on('click', handleClick);
alert('点击事件已绑定');
});
$('#unbindBtn').click(function() {
$('#bindBox').off('click', handleClick);
alert('点击事件已解绑');
});
});
</script>
</body>
</html>测试步骤:
- 保存文件为
events-practice.html - 用浏览器打开该文件
- 测试鼠标事件:将鼠标移入/移出"鼠标事件"盒子,点击盒子
- 测试键盘事件:在输入框中输入文本
- 测试表单事件:填写表单并提交
- 测试动态元素:点击"添加项目"按钮,然后点击新添加的项目
- 测试事件解绑:点击"绑定点击事件"按钮,点击"点击我"盒子,然后点击"解绑点击事件"按钮,再次点击"点击我"盒子
案例解析:
- 鼠标事件:使用
mouseenter、mouseleave和click事件 - 键盘事件:使用
keyup事件获取输入内容和按键信息 - 表单事件:使用
submit事件并阻止默认提交行为 - 动态元素:使用事件委托为动态添加的元素绑定事件
- 事件解绑:使用
off()方法解绑事件
新手易错点:
事件委托:
- 对于动态生成的元素,必须使用事件委托
- 事件委托的语法:
$(parent).on('event', 'childSelector', function() {})
阻止默认行为:
- 在表单提交等事件中,需要使用
event.preventDefault()阻止默认行为
- 在表单提交等事件中,需要使用
事件冒泡:
- 事件会从子元素冒泡到父元素
- 可以使用
event.stopPropagation()阻止事件冒泡
this关键字:
- 在事件处理函数中,
this指向触发事件的元素 - 可以使用
$(this)将其转换为jQuery对象
- 在事件处理函数中,
事件解绑:
- 如果使用命名函数绑定事件,可以精确解绑
- 如果使用匿名函数,只能解绑所有同类事件
