注意:使用 on() 方法添加的事件处理程序适用于当前及未来的元素(比如由脚本创建的新元素)。
多个事件绑定同一个函数
$(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");}
});
});
<script>
$(document).ready(function(){
$("div").on("click",function(){
$(this).slideToggle();
});
$("button").click(function(){
$("<p>This is a new paragraph.</p>").insertAfter("button");
});
});
</script>
<div style="background-color:yellow">
<p>This is a paragraph.</p>
<p>Click any p element to make it disappear. Including this one.</p>
<span>eeee</span>
<button>Insert a new p element after this button</button>
</div>
多个事件绑定同一个函数
$(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");}
});
});
<script>
$(document).ready(function(){
$("div").on("click",function(){
$(this).slideToggle();
});
$("button").click(function(){
$("<p>This is a new paragraph.</p>").insertAfter("button");
});
});
</script>
<div style="background-color:yellow">
<p>This is a paragraph.</p>
<p>Click any p element to make it disappear. Including this one.</p>
<span>eeee</span>
<button>Insert a new p element after this button</button>
</div>