jQuery后绑定事件注意事项

来源:互联网 发布:淘宝客服成功案例 编辑:程序博客网 时间:2024/04/29 01:33

注意:无论是JS还是jQuery在后绑定是事件时,都必须在页面加载完以后

JS:window.onload=function(){}

jQuery:$(function(){})

相同点:都表示页面加载后执行的代码

不同点:window.onload=function(){}若写多次,后者会覆盖前者,只有一个会生效,$(function(){})若写多次,都有效,在JS中调用多个js文件,且文件中都使用了window.onload=function(){},则后者会覆盖前者,只有一个会生效,而jQuery不会产生冲突,每个$(function(){})都有效

见下图:


jQuery中的后绑定事件代码如下:

<!DOCTYPE html><html><head><meta charset="UTF-8"><title>jQuery中的后绑定事件(必须在页面加载后)</title><style type="text/css">  .hidd{    display:none;  }</style><script type="text/javascript" src="../js/jQuery-1.11.1.js"></script><script type="text/javascript">  //$(function(){})类似于window.onload=function(){}  //区别:window.onload=function(){}若写多次,后者会覆盖前者,只有一个会生效  //$(function(){})若写多次,都有效  $(function(){$("input:button:first").click(function(e){//传入事件对象  console.log("123");  console.log(e);  //此事件对象被jQuery封装  //因为事件对象是由浏览器创建的,不同的浏览器创建的事件对象有区别  //jQuery接了了此麻烦,提供了统一的方法    //取消冒泡  e.stopPropagation();    //获取事件源  e.target});    });    //合成事件hover(fu(),fu())和toggle()  /*  hover:在JS中是伪类选择器,鼠标悬停时选中该元素  JS中的鼠标悬停事件是:onmouseover和onmouseout  jQuery中hover为合成事件,属于后绑定事件,不能在标签上直接声明属性  hover(function(){},function(){})传入两个参数:                鼠标悬停时执行的方法,鼠标移出时执行的方法, */  $(function(){//后绑定hover事件,此事件是jQuery特有的事件,必须使用jQuery后绑定事件    $("img").hover(      function(){    //$(this).width(250).height(250);   //√    //$(this).css("width","250px").css("height","250px");//√    //$(this).attr("width","250px").attr("height","250px");//√    //$(this).toggleClass("big");//假设big是变大的样式    //$(this).addClass("big");        //注意:对于width和height中不支持prop来设置    //$(this).prop("width","250px").prop("height","250px");//×      },      function(){        //$(this).width(218).height(218); //√        //$(this).css("width","218px").css("height","218px");//√        //$(this).attr("width","218px").attr("height","218px");//√        //$(this).removeClass("big");        //$(this).toggleClass("big");                //注意:对于width和height中不支持prop来设置        //$(this).prop("width","218px").prop("height","218px");×     });    //按钮2后绑定单击事件$("input:button:eq(1)").click(function(){      //让图片在显示与隐藏间切换(单击一次隐藏,再单击显示)      //方法(一)  //$("img:eq(0)").toggle();//√    //方法(二)  var flag = $("img:eq(0)").hasClass("hidd");  if(flag){$("img:eq(0)").removeClass("hidd");    }else{$("img:eq(0)").addClass("hidd");    }  //方法(三)  //$("img:eq(0)").toggleClass("hidd");      });  });</script></head><body>  <p>    <input type="button" value="按钮1" />    <input type="button" value="按钮2"/>  </p>  <p>    <img src="../images/01.jpg" />    <img src="../images/02.jpg" />  </p>  <p>最后</p></body></html>





0 0
原创粉丝点击