jquery绑定事件on的用法

语法

$(selector).on(event,childSelector,data,function,map)
参数描述
event 必需。规定要从被选元素移除的一个或多个事件或命名空间。

由空格分隔多个事件值。必须是有效的事件。
childSelector 可选。规定只能添加到指定的子元素上的事件处理程序(且不是选择器本身,比如已废弃的 delegate() 方法)。
data 可选。规定传递到函数的额外数据。
function 可选。规定当事件发生时运行的函数。
map 规定事件映射 ({event:function, event:function, ...}),包含要添加到元素的一个或多个事件,以及当事件发生时运行的函数。

1.绑定一个事件

$(document).on("click","#id",funciton(){

  alert("come here");

})

2.多事件绑定同一函数

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

3.绑定多个事件,绑定多函数

$(document).on({
  "mouseover": function () {
    $(this).css("background", "#000")

    //这里的$(this)指的是#id
  },
  "click": function () {
    $(this).css("height","100px")
  },
  "mouseout": function () {
    $(this).css("background", "red")
  }
}, "#id")

4.传递数据到函数

$("body").on({
  "click": toShow
  }, { name: "my name is sunnie" })
function toShow(info) {
  alert(info.data.name)
}

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

$(document).ready(function(){
  $("p").on("click",function(){
    $(this).css("background-color","pink");
  });
  $("button").click(function(){
    $("p").off("click");
  });
});
原文地址:https://www.cnblogs.com/sunnie-cc/p/6096941.html