- $("a[name=link]").click(function(event){
- //事件event;可用多个对象进行绑定用逗号分割 $("div,#link").click();
- event.stopPropagation();//不再派发事件
- });
$("a[name=link]").click(function(event){ //事件event;可用多个对象进行绑定用逗号分割 $("div,#link").click(); event.stopPropagation();//不再派发事件 });
- $("a[name=link]").keydown(function(event){//事件event
- if(event.keyCode=='13'){//记录点击的键盘编码 13为回车
- event.preventDefault();//不要执行与事件关联的默认动作
- }
- });
$("a[name=link]").keydown(function(event){//事件event if(event.keyCode=='13'){//记录点击的键盘编码 13为回车 event.preventDefault();//不要执行与事件关联的默认动作 } });//etc.
以上俩个例子,就是触发浏览器中的行为,还有很多,可参考jquety的文档,主要介绍是jquery所提供的其他方法如:bind,live,toggle,trigger,hover
1、bind()与unbind()
bind()是将元素进行行为上的绑定 例:
- $("a[name=link]").bind("click",function(event){//绑定click事件
- alert(event.pageX);//点击处x轴位置
- alert(event.pageY);//点击处Y轴位置
- });
- $("a[name=link]").bind("mouseenter mouseleave",function(){//绑定多个事件 鼠标移入移出
- //do something
- });
$("a[name=link]").bind("click",function(event){//绑定click事件 alert(event.pageX);//点击处x轴位置 alert(event.pageY);//点击处Y轴位置 }); $("a[name=link]").bind("mouseenter mouseleave",function(){//绑定多个事件 鼠标移入移出 //do something });uubind() 顾名思义 是解除绑定
- $("a[name=link]").unbind();//不加参数就解除此对象所有事件
$("a[name=link]").unbind();//不加参数就解除此对象所有事件需要注意一下,当我们用js去给文档添加元素的时候,bind已经绑定的动作是失效的,除非添加元素后再重新绑定,或者使用live()去进行绑定 例如
- <div id="demo">
- <div>
- $("#demo").append("<a href='javascript:void(0)' id='link'>text</a>");
- $("#link").bind("click",function(){//这种事不效果的
- alert(1);
- });
<div id="demo"> <div> $("#demo").append("<a href='javascript:void(0)' id='link'>text</a>"); $("#link").bind("click",function(){//这种事不效果的 alert(1); });2、live()是指附加处理器的元素,跟bind()用法基本一致,区别是live()可以使元素在任何时候添加,仍然响应事件
例子同bind() 就不举例说明了,注意区别就行了
3、toggle() 按照顺序依次调用指定的函数,然后重复调用,一般会做事件轮转切换,做动画效果
- $("a[name=link]").toggle(//点击一下会弹出1 再点击为2 。。3.。1.。2.。3.。。。
- function(){alert(1);},
- function(){alert(2);},
- function(){alert(3);}
- );
$("a[name=link]").toggle(//点击一下会弹出1 再点击为2 。。3.。1.。2.。3.。。。 function(){alert(1);}, function(){alert(2);}, function(){alert(3);} );如果没有参数为隐藏显示转换 可加参数 毫秒数或者slow fast字符串,详细请看jquery文档吧~
文档的例子很详细这就不在阐述了
4、trigger()是触发被选元素的事件
如当我们绑定了一个click事件,我们就可以通过trigger()去触发
- $("#link").bind("click",function(event){
- alert(1);
- });
- $("#link").trigger("click");
$("#link").bind("click",function(event){ alert(1); }); $("#link").trigger("click");5、hover()是同时绑定
mouseenter()
和 mouseleave()
的事件,对做鼠标移入移出的动画效果还是很方便的
- $("a[name=link]").hover(
- function () {
- $(this).append($("<span> ***</span>"));
- },
- function () {
- $(this).find("span:last").remove();
- }
- );