jQuery动态追加页面数据以及事件委托详解

2020-05-19 07:36:39易采站长站整理

但是在谷歌的浏览器中会出现以下的错误:

jquery.js:8475 XMLHttpRequest cannot load file:///C:/Users/%E9%95%BF%E5%AD%99%E4%B8%B9%E5%87%A4/Desktop/webtest/1.html. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

在IE10的环境下进行测试的,没问题。

解决办法就是装一个web服务器,然后将文件拷到项目中,以web服务器中的路径访问,就没有问题啦!形如http://localhost:8080/ajax/ajaxLoad.html

由于还有鼠标悬浮事件,当我们将鼠标悬浮在某个图片上时,就会出现文字,移出时,图片上的文字消失。


$(document).ready(function(){
$('div .photo').hover(function(){
$(this).find('.details').fadeTo('slow', 0.7);
},function(){
$(this).find('.details').fadeOut('slow');
})
});

或者可以将上面的代码组合起来减少冗余代码:


$(document).ready(function(){
$('div.photo').on('mouseenter mouseleave',
function(event){
var $details = $(this).find('.details');
if(event.type == 'mouseenter'){
$details.fadeTo('slow', 0.7);
//0.7代表的是透明度
}
else{
$details.fadeOut('slow');
}
})
});

当我们使用上面的两种代码为每个图片添加鼠标悬浮事件时,只有最初页面上的那些图片才会被绑定事件,而经过动态加载的图片上却没能绑定上事件。因为事件处理程序只会添加到调用方法时已经存在的元素上,像通过这种动态追加的元素,不会绑定那些事件。

所以有两种解决方案:

1. 在动态加载后重新绑定事件处理程序
2. 一开始就把事件绑定在存在的元素上,依赖于事件冒泡。

接下来就是使用jquery的委托方法;


$(document).ready(function(){
$('#gallery').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');
}
})
})

$(‘#gallery’).on(‘mouseenter mouseleave’, ‘div.photo’, function(event)中,在将’div.photo’作为第二个参数的情况下,.on()方法会把 this映射到 gallery中与该选择符匹配的元素。换句话说,就是this指向gallery中的 div class= ‘photo’的元素。

所以在最后追加的页面中,由于都属于gallery 下的元素,所以每一个图片都会加上相应的事件。

或许在你不知道要添加的页面属于哪个父级元素的话,可以将$(‘#gallery’).on( )中的’#gallery’替换成document。这样就不必担心选错容器。因为document是页面中所有元素的祖先。