jQuery on()方法

原文地址:http://www.cnblogs.com/leejersey/p/3545372.html

jquery中綁定事件一般使用bind,或者click,但是這隻能是對已經加載好的元素定義事件,那些後來添加插入的元素則需要另行綁定。在1.7版本以前使用live。但是在1.8版本以後推薦使用on。這裏介紹jQuery中如何給動態添加的元素綁定事件
在實際開發中會遇到要給動態生成的html元素綁定觸發事件的情況

例如

1
2
3
<div id="testdiv">
  <ul></ul>
</div>

需要給<ul>裏面動態添加的<li>標籤添加click事件
jquery 1.7版以前使用live動態綁定事件

1
2
$("#testdiv ul li").live("click",function(){
});

jquery 1.7版以後使用on動態綁定事件

1
2
3
$("#testdiv ul").on("click","li", function() {
     //do something here
 });

jQuery on()方法是官方推薦的綁定事件的一個方法。

$(selector).on(event,childSelector,data,function,map)

由此擴展開來的幾個以前常見的方法有.

bind()

  $("p").bind("click",function(){
    alert("The paragraph was clicked.");
  });

  $("p").on("click",function(){
    alert("The paragraph was clicked.");
  });

delegate()

  $("#div1").on("click","p",function(){
    $(this).css("background-color","pink");
  });

  $("#div2").delegate("p","click",function(){
    $(this).css("background-color","pink");
  });


live()

  $("#div1").on("click",function(){
    $(this).css("background-color","pink");
  });

  $("#div2").live("click",function(){
    $(this).css("background-color","pink");
  });

以上三種方法在jQuery1.8之後都不推薦使用,官方在1.9時已經取消使用live()方法了,所以建議都使用on()方法。

tip:如果你需要移除on()所綁定的方法,可以使用off()方法處理。

$(document).ready(function(){
  $("p").on("click",function(){
    $(this).css("background-color","pink");
  });
  $("button").click(function(){
    $("p").off("click");
  });
});

tip:如果你的事件只需要一次的操作,可以使用one()這個方法

$(document).ready(function(){
  $("p").one("click",function(){
    $(this).animate({fontSize:"+=6px"});
  });
});

trigger()綁定

$(selector).trigger(event,eventObj,param1,param2,...)
$(document).ready(function(){
  $("input").select(function(){
    $("input").after(" Text marked!");
  });
  $("button").click(function(){
    $("input").trigger("select");
  });
});

多個事件綁定同一個函數

$(document).ready(function(){
  $("p").on("mouseover mouseout",function(){
    $("p").toggleClass("intro");
  });
});

多個事件綁定不同函數

$(document).ready(function(){
  $("p").on({
    mouseover:function(){$("body").css("background-color","lightgray");},  
    mouseout:function(){$("body").css("background-color","lightblue");}, 
    click:function(){$("body").css("background-color","yellow");}  
  });
});

綁定自定義事件

$(document).ready(function(){
  $("p").on("myOwnEvent", function(event, showName){
    $(this).text(showName + "! What a beautiful name!").show();
  });
  $("button").click(function(){
    $("p").trigger("myOwnEvent",["Anja"]);
  });
});

傳遞數據到函數

function handlerName(event) 
{
  alert(event.data.msg);
}

$(document).ready(function(){
  $("p").on("click", {msg: "You just clicked me!"}, handlerName)
});

適用於未創建的元素

$(document).ready(function(){
  $("div").on("click","p",function(){
    $(this).slideToggle();
  });
  $("button").click(function(){
    $("<p>This is a new paragraph.</p>").insertAfter("button");
  });
});
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章