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


Posted in jQuery onMay 06, 2017

我们要执行的任务是页面起初有一部分图片,我们在底下有一个More Photos的链接,点击后,向当前页面后加载一部分图片,再点击该链接,继续加载,直到将我们列出的页面加载完成,此时该链接也消失了。

首先效果图如下:

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

这个只截取了最底下的一部分页面。在鼠标悬停在图片上时,还会有文字出现,鼠标移出时文字消失。
我们现在要做的就是点击底下的MorePhotos链接时,再加载一部分数据,然后再点击在加载一部分数据,直到数据加载完。
首先body中代码如下:

<div id = "container">
<h1> Photo Gallery</h1>

<div id = "gallery">
  <div class = "photo">
    <img src = "./images/1.jpg">
    <div class = "details">
      <div class = "description">The Cullin Mountains, Isle of skye ....</div>
      <div class = "date">12/24/2000</div>
      <div class = "photographer"> Alasdair Dougall</div>
    </div>
  </div>

  <div class = "photo">
    <img src = "./images/2.jpg">
    <div class = "details">
      <div class = "description">The Cullin Mountains, Isle of skye.... </div>
      <div class = "date">12/24/2000</div>
      <div class = "photographer"> Alasdair Dougall</div>
    </div>
  </div>

    <div class = "photo">
    <img src = "./images/3.jpg">
    <div class = "details">
      <div class = "description">The Cullin Mountains, Isle of skye.... </div>
      <div class = "date">12/24/2000</div>
      <div class = "photographer"> Alasdair Dougall</div>
    </div>
  </div>
//若干图片

</div>

 <div class = "link"><a id = "more-photos" href = "1.html"> More Photos >></a></div> 
</div>

然后在同一根目录下写几个HTML代码片段,用于加载。

如,我这有一个1.html代码如下

<div class = "photo">
    <img src = "./images/1.jpg">
    <div class = "details">
      <div class = "description">The Cullin Mountains, Isle of skye </div>
      <div class = "date">12/24/2000</div>
      <div class = "photographer"> Alasdair Dougall</div>
    </div>
  </div>

  <div class = "photo">
    <img src = "./images/2.jpg">
    <div class = "details">
      <div class = "description">The Cullin Mountains, Isle of skye </div>
      <div class = "date">12/24/2000</div>
      <div class = "photographer"> Alasdair Dougall</div>
    </div>
  </div>

    <div class = "photo">
    <img src = "./images/3.jpg">
    <div class = "details">
      <div class = "description">The Cullin Mountains, Isle of skye </div>
      <div class = "date">12/24/2000</div>
      <div class = "photographer"> Alasdair Dougall</div>
    </div>
  </div>

    <div class = "photo">
    <img src = "./images/4.jpg">
    <div class = "details">
      <div class = "description">The Cullin Mountains, Isle of skye </div>
      <div class = "date">12/24/2000</div>
      <div class = "photographer"> Alasdair Dougall</div>
    </div>
  </div>

    <div class = "photo">
    <img src = "./images/5.jpg">
    <div class = "details">
      <div class = "description">The Cullin Mountains, Isle of skye </div>
      <div class = "date">12/24/2000</div>
      <div class = "photographer"> Alasdair Dougall</div>
    </div>
  </div>

    <div class = "photo">
    <img src = "./images/6.jpg">
    <div class = "details">
      <div class = "description">The Cullin Mountains, Isle of skye </div>
      <div class = "date">12/24/2000</div>
      <div class = "photographer"> Alasdair Dougall</div>
    </div>
  </div>

在这个HTML片段中我引入了6个图片。其他的片段如2.html等等都可以仿照上面的这个来写。在定义好了许多个HTML片段后,利用jQuery进行动态追加数据。

首先引入一个jquery库 http://libs.baidu.com/jquery/1.9.0/jquery.js

<script>
  $(document).ready(function(){
  //首先定义一个变量来记录当前是多少页
    var pageNum = 1;

    //给链接添加点击事件
    $("#more-photos").click(function(event){
      event.preventDefault();
      var $link = $(this);

      //获得当前所点链接的url
      var url = $link.attr('href');

      //如果该链接的url存在,进行页面追加
      if(url){
        $.get(url, function(data){
          $("#gallery").append(data);
        });

    pageNum ++;
  //总共有十个片段要追加,名称分别为1.html,2.html ...10.html
    当当前页面的总数小于总数时,进行链接更新。
    if(pageNum < 10){
      $link.attr('href', './'+pageNum+'.html');
        }

    //当将所有片段追加完成后,移除链接。
      else{
        $link.remove();
      }
      }
    })
  });

以上的代码就可以进行动态的向页面追加数据了。

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

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是页面中所有元素的祖先。

但使用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>

  <script>
  $(document).ready(function(){

    var pageNum = 1;
    $("#more-photos").click(function(event){
      event.preventDefault();
      var $link = $(this);
      var url = $link.attr('href');
      console.log(url);
      if(url){
        $.get(url, function(data){
          $("#gallery").append(data);
        });

        pageNum ++;
        if(pageNum < 4){
          $link.attr('href', './'+pageNum+'.html');
        }


      else{
        $link.remove();
      }
      }
    })
  })

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

  $(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');
      }
    })
  })

  </script>
</head>
<body>
<div id = "container">
<h1> Photo Gallery</h1>

<div id = "gallery">
  <div class = "photo">
    <img src = "./images/1.jpg">
    <div class = "details">
      <div class = "description">The Cullin Mountains, Isle of skye ....</div>
      <div class = "date">12/24/2000</div>
      <div class = "photographer"> Alasdair Dougall</div>
    </div>
  </div>

  <div class = "photo">
    <img src = "./images/2.jpg">
    <div class = "details">
      <div class = "description">The Cullin Mountains, Isle of skye.... </div>
      <div class = "date">12/24/2000</div>
      <div class = "photographer"> Alasdair Dougall</div>
    </div>
  </div>

    <div class = "photo">
    <img src = "./images/3.jpg">
    <div class = "details">
      <div class = "description">The Cullin Mountains, Isle of skye.... </div>
      <div class = "date">12/24/2000</div>
      <div class = "photographer"> Alasdair Dougall</div>
    </div>
  </div>

    <div class = "photo">
    <img src = "./images/4.jpg">
    <div class = "details">
      <div class = "description">The Cullin Mountains, Isle of skye .....</div>
      <div class = "date">12/24/2000</div>
      <div class = "photographer"> Alasdair Dougall</div>
    </div>
  </div>

    <div class = "photo">
    <img src = "./images/5.jpg">
    <div class = "details">
      <div class = "description">The Cullin Mountains, Isle of skye ....</div>
      <div class = "date">12/24/2000</div>
      <div class = "photographer"> Alasdair Dougall</div>
    </div>
  </div>

    <div class = "photo">
    <img src = "./images/6.jpg">
    <div class = "details">
      <div class = "description">The Cullin Mountains, Isle of skye ...</div>
      <div class = "date">12/24/2000</div>
      <div class = "photographer"> Alasdair Dougall</div>
    </div>
  </div>

    <div class = "photo">
    <img src = "./images/7.jpg">
    <div class = "details">
      <div class = "description">The Cullin Mountains, Isle of skye.... </div>
      <div class = "date">12/24/2000</div>
      <div class = "photographer"> Alasdair Dougall</div>
    </div>
  </div>

    <div class = "photo">
    <img src = "./images/8.jpg">
    <div class = "details">
      <div class = "description">The Cullin Mountains, Isle of skye..... </div>
      <div class = "date">12/24/2000</div>
      <div class = "photographer"> Alasdair Dougall</div>
    </div>
  </div>

    <div class = "photo">
    <img src = "./images/9.jpg">
    <div class = "details">
      <div class = "description">The Cullin Mountains, Isle of skye ...... </div>
      <div class = "date">12/24/2000</div>
      <div class = "photographer"> Alasdair Dougall</div>
    </div>
  </div>

    <div class = "photo">
    <img src = "./images/10.jpg">
    <div class = "details">
      <div class = "description">The Cullin Mountains, Isle of skye </div>
      <div class = "date">12/24/2000</div>
      <div class = "photographer"> Alasdair Dougall</div>
    </div>
  </div>

    <div class = "photo">
    <img src = "./images/11.jpg">
    <div class = "details">
      <div class = "description">The Cullin Mountains, Isle of skye </div>
      <div class = "date">12/24/2000</div>
      <div class = "photographer"> Alasdair Dougall</div>
    </div>
  </div>

    <div class = "photo">
    <img src = "./images/12.jpg">
    <div class = "details">
      <div class = "description">The Cullin Mountains, Isle of skye </div>
      <div class = "date">12/24/2000</div>
      <div class = "photographer"> Alasdair Dougall</div>
    </div>
  </div>


    <div class = "photo">
    <img src = "./images/13.jpg">
    <div class = "details">
      <div class = "description">The Cullin Mountains, Isle of skye </div>
      <div class = "date">12/24/2000</div>
      <div class = "photographer"> Alasdair Dougall</div>
    </div>
  </div>

    <div class = "photo">
    <img src = "./images/14.jpg">
    <div class = "details">
      <div class = "description">The Cullin Mountains, Isle of skye </div>
      <div class = "date">12/24/2000</div>
      <div class = "photographer"> Alasdair Dougall</div>
    </div>
  </div>

    <div class = "photo">
    <img src = "./images/15.jpg">
    <div class = "details">
      <div class = "description">The Cullin Mountains, Isle of skye </div>
      <div class = "date">12/24/2000</div>
      <div class = "photographer"> Alasdair Dougall</div>
    </div>
  </div>

</div>

 <div class = "link"><a id = "more-photos" href = "1.html"> More Photos >></a></div> 
</div>
</body>
</html>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

jQuery 相关文章推荐
使用jQuery实现鼠标点击左右按钮滑动切换
Aug 04 jQuery
用jquery获取select标签中选中的option值及文本的示例
Jan 25 jQuery
通过jquery toggleClass()属性制作文章段落更改背景颜色
May 21 jQuery
Angular5中调用第三方库及jQuery的添加的方法
Jun 07 jQuery
使用jquery模拟a标签的click事件无法实现跳转的解决
Dec 04 jQuery
jQuery判断自定义属性data-val用法示例
Jan 07 jQuery
Easyui 关闭jquery-easui tab标签页前触发事件的解决方法
Apr 28 jQuery
Jquery属性的获取/设置及样式添加/删除操作技巧分析
Dec 23 jQuery
jquery实现轮播图特效
Apr 12 jQuery
jQuery 选择方法及$(this)用法实例分析
May 19 jQuery
JQuery+drag.js上传图片并且实现图片拖曳
Nov 18 jQuery
Jquery+javascript实现支付网页数字键盘
Dec 21 jQuery
jquery点赞功能实现代码 点个赞吧!
May 29 #jQuery
jQuery extend()详解及简单实例
May 06 #jQuery
jquery仿微信聊天界面
May 06 #jQuery
简单实现jQuery弹幕效果
May 06 #jQuery
jquery实现提示语淡入效果
May 05 #jQuery
Jquery获取radio选中的值
May 05 #jQuery
jQuery实现简单的抽奖游戏
May 05 #jQuery
You might like
关于PHP的相似度计算函数:levenshtein的使用介绍
2013/04/15 PHP
解密ThinkPHP3.1.2版本之模板继承
2014/06/19 PHP
PHP中的正则表达式实例详解
2017/04/25 PHP
PHP使用PDO实现mysql防注入功能详解
2019/12/20 PHP
jQuery checkbox全选/取消全选实现代码
2009/11/14 Javascript
简单实用的js调试logger组件实现代码
2010/11/20 Javascript
jquery 鼠标滑动显示详情应用示例
2014/01/24 Javascript
js怎么覆盖原有方法实现重写
2014/09/04 Javascript
jQuery验证元素是否为空的两种常用方法
2015/03/17 Javascript
详解jQuery向动态生成的内容添加事件响应jQuery live()方法
2015/11/02 Javascript
原生javascript实现图片无缝滚动效果
2016/02/12 Javascript
利用jQuery实现一个简单的表格上下翻页效果
2017/03/14 Javascript
webpack打包react项目的实现方法
2018/06/21 Javascript
在JS循环中使用async/await的方法
2018/10/12 Javascript
详解超简单的react服务器渲染(ssr)入坑指南
2019/02/28 Javascript
Vue基础学习之项目整合及优化
2019/06/02 Javascript
JS实现图片幻灯片效果代码实例
2020/05/21 Javascript
Vuex中的Mutations的具体使用方法
2020/06/01 Javascript
深入理解javascript中的this
2021/02/08 Javascript
Python计算回文数的方法
2015/03/11 Python
Python3编程实现获取阿里云ECS实例及监控的方法
2017/08/18 Python
python3使用QQ邮箱发送邮件
2020/05/20 Python
手把手教你使用Python创建微信机器人
2019/04/29 Python
Python 合并多个TXT文件并统计词频的实现
2019/08/23 Python
python logging通过json文件配置的步骤
2020/04/27 Python
五分钟学会怎么用Pygame做一个简单的贪吃蛇
2021/01/06 Python
加拿大租车网站:Enterprise Rent-A-Car
2018/07/26 全球购物
Agoda中文官网:安可达(低价预订全球酒店)
2021/01/18 全球购物
struct与class的区别
2014/02/03 面试题
介绍一下mysql的日期和时间函数
2013/03/28 面试题
销售业务员岗位职责
2014/01/29 职场文书
开学寄语大全
2014/04/08 职场文书
债务纠纷委托书范本
2014/10/14 职场文书
2015年学校教育教学工作总结
2015/04/22 职场文书
食堂管理制度范本
2015/08/04 职场文书
mysql insert 存在即不插入语法说明
2022/03/25 MySQL