1、用法及说明
on() 方法在被选元素及子元素上添加一个或多个事件处理程序。
说明:自 jQuery 版本 1.7 起,on() 方法是 bind()、live() 和 delegate() 方法的新的替代品。我们推荐用on(),官方在1.9时已经取消使用live()方法了
提示:如需移除事件处理程序,请使用 off() 方法。
提示:如需添加只运行一次的事件然后移除,请使用 one() 方法。
2、语法
$(selector).on(event,childSelector,data,function,map)
参数 | 描述 |
---|---|
event | 必需。规定要从被选元素移除的一个或多个事件或命名空间。 由空格分隔多个事件值。必须是有效的事件。 |
childSelector | 可选。规定只能添加到指定的子元素上的事件处理程序(且不是选择器本身,比如已废弃的 delegate() 方法)。 |
data | 可选。规定传递到函数的额外数据。 |
function | 可选。规定当事件发生时运行的函数。 |
map | 规定事件映射 ({event:function, event:function, ...}),包含要添加到元素的一个或多个事件,以及当事件发生时运行的函数。 |
3、实例
a、如何使用 on() 来达到与 bind() 相同的效果
<script>
$(document).ready(function(){
$("#div1").on("click",function(){
$(this).css("background-color","pink");
});
$("#div2").bind("click",function(){
$(this).css("background-color","pink");
});
});
</script>
b、如何使用 on() 来达到与delegate()相同的效果
<script>
$(document).ready(function(){
$("#div1").on("click","p",function(){
$(this).css("background-color","pink");
});
$("#div2").delegate("p","click",function(){
$(this).css("background-color","pink");
});
});
</script>
c、如何使用 on() 来达到与 live() 相同的效果 //官方在1.9时已经取消使用live()方法了
<script>
$(document).ready(function(){
$("#div1").on("click",function(){
$(this).css("background-color","pink");
});
$("#div2").live("click",function(){
$(this).css("background-color","pink");
});
});
</script>
d、如何向元素添加多个事件处理程序
<script>
$(document).ready(function(){
$("p").on("mouseover mouseout",function(){
$("p").toggleClass("intro");
});
});
</script>
e、如何使用 map 参数向被选元素添加多个事件处理程序
<script>
$(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");}
});
});
</script>
f、如何在元素上添加自定义命名空间事件
<script>
$(document).ready(function(){
$("p").on("myOwnEvent", function(event, showName){
$(this).text(showName + "! What a beautiful name!").show();
});
$("button").click(function(){
$("p").trigger("myOwnEvent",["Anja"]);
});
});
</script>
g、如何向函数传递数据。
<script>
function handlerName(event)
{
alert(event.data.msg);
}
$(document).ready(function(){
$("p").on("click", {msg: "You just clicked me!"}, handlerName)
});
</script>
h、向未来元素添加时间处理程序
<script>
$(document).ready(function(){
$("div").on("click","p",function(){
$(this).slideToggle();
});
$("button").click(function(){
$("<p>This is a new paragraph.</p>").insertAfter("button");
});
});
</script>
i、如何使用 off() 方法移除事件处理程序
<script>
$(document).ready(function(){
$("p").on("click",function(){
$(this).css("background-color","pink");
});
$("button").click(function(){
$("p").off("click");
});
});
</script>
注:来源w3cschool