1. 程式人生 > >jQuery後繫結事件注意事項

jQuery後繫結事件注意事項

注意:無論是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>