1.事件绑定
bind(type [, data] , fn)方法有三个参数,其中第二个参数是可选参数,作为event.data属性值传递给事件对象的额外数据对象。与ready()方法一样,bind()方法也可以多次调用
移除事件为unbind()方法
例:1.
$(function() {
$("#panel h5.head").bind("click",function () {
if($(this).next().is(":visible")){
$(this).next().hide();
}else{
$(this).next().show();
}
});
});
2.
$(function () {
$("#panel h5.head").bind("mouseover",function () {
$(this).next().show();
}).bind("mouseout",function () {
$(this).next().hide();
});
});
2.合成事件:hover(enter,leave)方法和toggle(fn1,fn2,…fnN)方法
2.1hover()方法用于模拟光标悬停事件,当光标移动到元素上时,会触发第一个函数(enter),当光标移除元素时,触发第二个函数(leave)
例:
$(function () {
$("#panel h5.head").hover(function (){
$(this).next().show();
},function () {
$(this).next().hide();
});
});
2.2toggle()方法用于模拟鼠标连续单击事件,第一次单击,触发指定的第一个函数(fn1),第二次单击同一元素,触发指定的第二个函数(fn2)。。。。随后每次单击都重复对这几个函数轮番调用
注:toggle()方法还可切换元素的可见状态
例:
$(function () {
$("#panel h5.head").toggle(function () {
$(this).addClass("highLight");
$(this).next().toggle();
},function () {
$(this).removeClass("highLight");
$(this).next().toggle();
});
});
3.事件冒泡
在jQuery中分别提供了stopPropagation()方法来停止事件冒泡和preventDefault()事件来阻止元素的默认行为
例:1.停止事件冒泡
$(function () {
$("span").bind("click",function (event) {
...
event.stopPropagation();
});
});
2.阻止元素默认行为(如:阻止表单提交)
$(function () {
$("span").bind("click",function (event) {
...
event.preventDefault();
});
});
注:如果想同时对事件对象停止冒泡和默认行为,可以再事件处理函数中返回false
例:
$("a").click(function (event) {
...
return false;
});