事件的冒泡
事件的冒泡是从子标签向父标签传递
<script>
$(function () {
// 事件的冒泡
// 事件的传递从子向父传递
var $grandfather = $('.grandfather'),
$father = $('.father'),
$son = $('.son');
$son.click(function () {
alert('son');
});
$father.click(function () {
alert('father');
});
$grandfather.click(function () {
alert('grandfather');
});
});
</script>
事件的阻止
防止由于事件冒泡导致父标签接收事件
<script>
$(function () {
// 事件的冒泡
// 事件的传递从子向父传递
var $grandfather = $('.grandfather'),
$father = $('.father'),
$son = $('.son');
$son.click(function (event) {
alert('son');
// 点击完子后,父和父父不能接收到事件
// 阻止事件的冒泡
event.stopPropagation();
// 阻止系统的提交 或者使用return flase;
event.preventDefault();
});
$father.click(function () {
alert('father');
// 阻止事件的冒泡
event.stopPropagation();
});
$grandfather.click(function () {
alert('grandfather');
// 阻止事件的冒泡
event.stopPropagation();
});
});
</script>
事件的委托
由于子标签是动态可变的,可以委托父标签来设置子标签的事件
<script>
$(function () {
var $ul = $('.box');
// 事件委托 参数:子标签、委托事件、事件回调函数
$ul.delegate('li', 'click', function () {
$(this).css({
'color': 'red'
});
});
var sContent = $ul.html();
$ul.html(sContent + '<li>6</li>');
});
</script>