bind()
bind(type [,data],fn);
第二個參數(shù)可選谆刨,傳遞給事件對象等額外數(shù)據(jù)對象 ?碑宴?
<ul class="test">
<li title='香蕉'><strong class="bn">香蕉</strong></li>
<li title='香蕉'><strong>蘋果</strong></li>
</ul>
<script >
$(function(){
$("li:eq(0)").bind('click',function(){
var ap = $(this).next();//this是攜帶相應(yīng)行為的DOM元素
if( ap.is(":visible") ){
ap.hide();
}else{
ap.show();
}
});
});
</script>
簡寫綁定事件
$().click(function(){});
綁定多個事件直接后面加.
$().mouseover(function(){}).mouseout(function(){});
hover()合成事件
hover(enter,leave);
$(function(){
$('.test').hover(function(){
console.log('鼠標經(jīng)過');
},function(){
console.log('鼠標離開');
});
});
toggle()合成事件
模擬鼠標連續(xù)點擊事件
toggel(fn1,fn2,····fnN);依次促發(fā) 循環(huán)調(diào)用
$(function(){
$('.test').toggle(function(){
console.log('第一次');
},function(){
console.log('第二次');
},function(){
console.log('還可以很多次');
});
});
event 事件對象
方法 | 介紹 | 示例 |
---|---|---|
event.type | 獲取事件類型 | |
event.preventDefault() | 阻止默認事件 | |
event.stopPropagation() | 阻止事件冒泡 | |
event.target() | 獲取促發(fā)事件的元素 | |
event.relatedTarget | mouseout和mouseover所發(fā)生的元素 | |
event.pageX event.pageY | 光標相對于頁面x軸和y軸的坐標 | |
event.which | 獲取鼠標鼠標的左中右鍵和鍵盤的按鍵 | |
event.metaKey | 鍵盤中獲取<ctrl>鍵 |
還有更多其他方法 自己查
移除事件
可以為同一個元素綁定多個事件裆甩,也可以為多個元素綁定同一個事件
$(function(){
$('.test').bind('click',function(){
$('.test').append("我是1")
}).bind('click',function(){
$('.test').append("我是2")
}).bind('click',function(){
$('.test').append("我是3")
});
$('.test').unbind('click');//移除綁定事件 參數(shù)可以為空
});
若要刪除指定的綁定元素 則需要為匿名處理函數(shù)指定一個變量
$(function(){
$('.test').bind('click',myFun1 = function(){
$('.test').append("我是1")
}).bind('click',myFun2 = function(){
$('.test').append("我是2")
}).bind('click',myFun3 = function(){
$('.test').append("我是3")
});
$('.test').unbind('click',myFun2);//添加命名
});
one()方法 函數(shù)只在第一次用戶操作時候執(zhí)行
one( type, [data],f n );
$(function(){
$('.test').one('click',myFun1 = function(){
$('.test').append("我是1")
});
});
1.7后新增 on(),off(),delegate(),undelegate()
--事件命名空間以及不同命名空間的執(zhí)行方法--
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>doc測試學習</title>
<script src="http://cdn.staticfile.org/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
<ul class="test">
<li title='香蕉'><strong class="bn">香蕉</strong></li>
<li title='香蕉'><strong>蘋果</strong></li>
</ul>
<span >執(zhí)行不在命名空間的事件</span>
<b>執(zhí)行自定義事件</b>
<i>移除自定義事件<i/>
<script >
$(function(){
$('.test').bind('click',function(){
console.log(1);
});
$('.test').bind('click.plugin',function(){
console.log(2);
});
$('.test').bind('dbclick',function(){
console.log(3);
});//dbclick是自定義事件 可以通過trigger()來觸發(fā)
$('span').click(function(){
$('.test').trigger('click!');
//click! !表示不包含在命名空間內(nèi)的click方法
//去掉之斯! 則表示兩者都被觸發(fā)
});
$('b').click(function(){
$('.test').trigger('dbclick');
//執(zhí)行自定義事件
});
$('i').click(function(){
$('.test').unbind('dbclick');
//移除dbclick自定義事件
});
});
</script>
</body>
</html>