bind的一般格式:
复制代码
1
2$("#id").bind("click",function(){})
on的一般格式:
复制代码
1
2$("#id").on("click",".class",function(){})
从写法上看,on比bind多了一个对子标签进行选择的selector(非必须),这就是它们的区别,下面通过实例进行说明:
复制代码
1
2
3
4
5
6
7<p name="p">p_Test1</p> <p name="p">p_Test2</p> <div> <input type="button" value="btn"/> <input type="text"/> </div>
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13//p标签绑定click事件 $("p").bind("click", function () { alert($(this)[0].innerHTML); }); //div标签绑定click事件 $("div").on("click", function () { alert($(this).val()); }); //div标签下type=button的input标签绑定click事件 $("div").on("click", "[type='button']", function () { alert($(this).val()); });
情景一:on将子元素事件委托给父元素进行处理
复制代码
1
2
3
4
5
6
7
8
9
10<div class="content1"> <div class="child"></div> </div> <div class="content2"> <div class="child"></div> </div> <div class="content3"> <div class="child"></div> </div>
复制代码
1
2
3
4
5
6
7$(".child").bind("click",function () { //bind只能给所有的.child类所对应的元素统一添加事件 }) $(".content1").on("click",".child",function () { //on在父元素上绑定指定子元素的事件 })
情景二:on为动态添加的元素绑定事件(例1)
复制代码
1
2
3<div class="content1">123</div> <div class="content2">456</div>
复制代码
1
2
3
4
5
6
7
8
9$(".content1").addClass("show-red"); $(".content2").addClass("show-yellow"); /*$(".show-red").bind("click",function () { //bind只在页面渲染时添加一次事件 })*/ $(".content1").on("click",".show-red",function () { //on可以给动态添加的元素添加事件 })
情景三:on为动态添加的元素绑定事件(例2)
复制代码
1
2
3<div id="div"></div> <button onclick="add()">button</button>
复制代码
1
2
3
4
5
6
7
8
9$(function () { $("#div").on("click",".child",function () { alert(); }) }) function add() { $("#div").append("<div class="child">Child</div>"); }
最后
以上就是淡淡镜子最近收集整理的关于jQuery中on与bind的区别的全部内容,更多相关jQuery中on与bind内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复