jQuery的事件处理
页面载入事件
(1)JavaScript的页面载入事件:window.onload
(2)jQuery的页面载入事件(入口函数):$(function(){ js代码 })
事件绑定
(1)jQuery常用事件方法
   (2)语法格式
$(selector).bind('事件类型',function(){
处理代码
})
或者
$(selector).事件名(function(){
处理代码
})
例如:
<label>
用户名:
<input type="text" id="username">
</label>
<br><br>
<label>
密码:
<input type="password" id="pwd">
</label>
<br><br>
<button type="button" id="btn_submit">提交</button>
<button type="button" id="btn_reset">重置</button>
$('#btn_reset').bind('click',function(){
$('#username').val('')
$('#pwd').val('')
})
反绑定
如果你想要取消元素上绑定的事件,就可以使用反绑定的方法,这样元素就监听不到相应的事件。
方法:
(1)取消元素上绑定的所有事件:$(selector).unbind()
(2)取消元素上绑定的指定事件:$(selector).unbind('事件名')
例如:
紧接上面的例子
$('#btn_reset').unbind('click')
这样一来,重置按钮就不起作用了,无法重置输入框里面的内容。
一次性事件的绑定
想要一个控件或者一个元素只能使用一次,就可以用到一次性事件的绑定。
语法格式:
$(selector).one('事件类型',function(){
处理代码
})
例如:
紧接上例:
$('#btn_reset').one('click',function(){
$('#username').val('')
$('#pwd').val('')
})
jQuery事件对象
当事件被触发时,就会有事件对象的产生,在事件处理函数中可以使用参数来接收事件对象。
例如:
$('div').bind('click',function(event){
console.log(event)
alert(event.target)
console.log(event.pageX+','+event.pageY)
})
 其中:
type :事件类型 target :事件对象 pageX 、pageY :在鼠标事件中鼠标相对于页面原点(最左上角的点)的x、y坐标
鼠标悬停事件
语法格式:
$(selector).hover(over,out)
(1)over :回调函数,表示鼠标悬停时调用的函数 (2)out :回调函数,表示鼠标离开时调用的函数
例如:
<img src="../images/8.png.jpeg" alt="" width="300" height="200"> //选取一张图片
$('img').hover(function(event){
$('img').attr('src','../images/9.gif')
console.log(event.type)
},function(event){
$('img').attr('src','../images//8.png.jpeg')
console.log(event.type)
}
)
效果: 
|