引言:
JQuery的事件绑定与插件
事件绑定
- JQuery标准的绑定方式
jqObj.事件方法(回调函数)
1 2 3 4 5 6 7 8 9 10 11 12
| $("button").click(function () { alert(1); }).mouseover(function () { alert("鼠标来了"); }).mouseleave(function () { alert("鼠标离开"); }) $("#input1").focus();
$("#form1").submit();
|
- on绑定事件/off解除绑定
jqObj.on("事件名称",回调函数)
jqObj.off("事件名称")
1 2 3 4 5 6
| $("button:eq(0)").on("click",function () { alert("我被点击了"); $("button:eq(0)").off("click"); })
|
- 事件切换:toggle
1.9版本后移除,可以使用插件migrate
来恢复此功能
jqObj.toggle(fn1,fn2...)
点击第一下执行fn1,第二下点fn2
1 2 3 4 5 6
| $("button").toggle(function () { alert(1); },function () { alert(2); })
|
插件
增强JQuery功能
,jQuery提供了两种插件的方式
$.fn.extend(obj)
对象级别插件
增强通过jQuery获取的对象的功能
$.extend(obj)
全局级别插件
增强jQuery对象自身的功能
小案例
使用插件实现全选的功能
1 2 3 4 5
| <button class="button1">全选</button> <button class="button2">取消全选</button> <input type="checkbox">一个 <input type="checkbox">二个 <input type="checkbox">三个
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| $.fn.extend({ check:function () { this.prop("checked",true); }, unCheck:function () { this.prop("checked",false); } });
$(".button1").click(function () { $("input[type='checkbox']").check(); }); $(".button2").click(function () { $("input[type='checkbox']").unCheck(); })
|