现在的位置: 网页制作教程网站制作教程 >正文
jquery相关教程

jQuery on()方法介绍

发表于2017/5/4 网站制作教程 0条评论 ⁄ 热度 1,875℃

jQuery on()方法是官方推荐的绑定事件的一个方法。

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

由此扩展开来的几个以前常见的方法有:

bind()

javascript 代码:
  1. $("p").bind("click",function(){
  2. alert("The paragraph was clicked.");
  3. });
  4. $("p").on("click",function(){
  5. alert("The paragraph was clicked.");
  6. });

delegate()

javascript 代码:
  1. $("#div1").on("click","p",function(){
  2. $(this).css("background-color","pink");
  3. });
  4. $("#div2").delegate("p","click",function(){
  5. $(this).css("background-color","pink");
  6. });

live()

javascript 代码:
  1. $("#div1").on("click",function(){
  2. $(this).css("background-color","pink");
  3. });
  4. $("#div2").live("click",function(){
  5. $(this).css("background-color","pink");
  6. });

以上三种方法在jQuery1.8之后都不推荐使用,官方在1.9时已经取消使用live()方法了,所以建议都使用on()方法。

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

javascript 代码:
  1. $(document).ready(function(){
  2.   $("p").on("click",function(){
  3.     $(this).css("background-color","pink");
  4.   });
  5.   $("button").click(function(){
  6.     $("p").off("click");
  7.   });
  8. });

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

javascript 代码:
  1. $(document).ready(function(){
  2.  $("p").one("click",function(){
  3.   $(this).animate({fontSize:"+=6px"});
  4.  });
  5. });

trigger()绑定

javascript 代码:
  1. $(selector).trigger(event,eventObj,param1,param2,...)
  2. $(document).ready(function(){
  3.   $("input").select(function(){
  4.     $("input").after(" Text marked!");
  5.   });
  6.   $("button").click(function(){
  7.     $("input").trigger("select");
  8.   });
  9. });

多个事件绑定同一个函数

javascript 代码:
  1. $(document).ready(function(){
  2. $("p").on("mouseover mouseout",function(){
  3. $("p").toggleClass("intro");
  4. });
  5. });

多个事件绑定不同函数

javascript 代码:
  1. $(document).ready(function(){
  2. $("p").on({
  3. mouseover:function(){$("body").css("background-color","lightgray");},
  4. mouseout:function(){$("body").css("background-color","lightblue");},
  5. click:function(){$("body").css("background-color","yellow");}
  6. });
  7. });

绑定自定义事件

javascript 代码:
  1. $(document).ready(function(){
  2. $("p").on("myOwnEvent", function(event, showName){
  3. $(this).text(showName + "! What a beautiful name!").show();
  4. });
  5. $("button").click(function(){
  6. $("p").trigger("myOwnEvent",["Anja"]);
  7. });
  8. });

传递数据到函数

javascript 代码:
  1. function handlerName(event)
  2. {
  3. alert(event.data.msg);
  4. }
  5. $(document).ready(function(){
  6. $("p").on("click", {msg: "You just clicked me!"}, handlerName)
  7. });

适用于未创建的元素

javascript 代码:
  1. $(document).ready(function(){
  2. $("div").on("click","p",function(){
  3. $(this).slideToggle();
  4. });
  5. $("button").click(function(){
  6. $("<p>This is a new paragraph.</p>").insertAfter("button");
  7. });
  8. });
  • 暂无评论