但使用document有弊端:
当DOM嵌套结构很深,事件冒泡通过大量的祖先元素会有较大的性能损失。
但是还会有其他的原因让我们选择document作为委托作用域。
一般来说,只有当相应的DOM元素加载完毕,才会给它绑定事件处理程序。这就是为什么我们要把代码放到$(document).ready(function(){}内部的原因。可是document元素是随着页面加载几乎就立即可以调用的。把处理程序绑定到document不用等到完整的DOM构建结束。如上面的代码可以写为:‘
(function($){
$(document).on('mouseenter mouseleave', 'div.photo', function(event){ var $details = $(this).find('.details');
if(event.type == 'mouseenter'){
$details.fadeTo('slow', 0.7);
}
else{
$details.fadeOut('slow');
}
})
})(jQuery);
因为没有等到整个文档就绪,所以可以确保所有<div class= ‘photo’>元素只要呈现在页面上,就可以应用mouseenter 和mouseleave行为。
上面就是关于利用jQuery动态追加页面数据以及事件委托的全部知识。下面附上源代码;
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8" />
<title>动态加载</title>
<script type="text/javascript" src = "http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<style type="text/css">
*{
margin: 0px;
padding: 0px;
} #container{
position: relative;
width: 1300px;
margin: 0 auto;
/*background-color: #ccc;
height: auto;*/
}
#gallery{
position: relative;
width: 1300px;
margin: 0 auto;
}
.details{
display: none;
}
.photo{
padding: 20px;
border-radius: 5px;
border:1px solid #ccc;
box-shadow: 0 0 5px #ccc;
float: left;
margin: 8px;
}
.photo img{
/*z-index: 1;*/
width: 200px;
height: 300px;
clear: both;
}
.photo .details{
position: absolute;
z-index: 2;
padding-left: 20px;
margin-top:-200px;
/*clear: both;*/
overflow: hidden;
}
.description{
overflow: hidden;
width: 200px;
color: lightgreen;
font-size: 18px;
font-weight: bold;
}
.date{
font-size:16px;
margin: 20px 0px;
color: red;
}
.photographer{
font-size:14px;
font-family: "Arial" ;
}
.link a{
clear: both;
text-decoration: none;
padding-left: 90%;
}
h1{
text-align: center;
}
</style>










