jQuery 是为事件处理特别设计的。
什么是事件?
页面对不同访问者的响应叫做事件。
事件处理程序指的是当 HTML 中发生某些事件时所调用的方法。
实例:
在元素上移动鼠标。
选取单选按钮
点击元素
在事件中经常使用术语"触发"(或"激发")例如: "当您按下按键时触发 keypress 事件"。
常见 DOM 事件:
![](https://i-blog.csdnimg.cn/blog_migrate/81ff9a48d06ee9ac8442f2192d7d962e.png)
jQuery 事件方法语法
在 jQuery 中,大多数 DOM 事件都有一个等效的 jQuery 方法。
页面中指定一个点击事件:
![](https://i-blog.csdnimg.cn/blog_migrate/67eb908b387bf85e7d7b15f5f2095115.png)
下一步是定义了点击后触发事件。您可以通过一个事件函数实现:
![](https://i-blog.csdnimg.cn/blog_migrate/9da9027254de79c47caa69e77ee48a67.png)
常用的 jQuery 事件方法
$(document).ready()
$(document).ready() 方法允许我们在文档完全加载完后执行函数。
click()
click() 方法是当按钮点击事件被触发时会调用一个函数。
该函数在用户点击 HTML 元素时执行。
在下面的实例中,当点击事件在某个 <p> 元素上触发时,隐藏当前的 <p> 元素:
![](https://i-blog.csdnimg.cn/blog_migrate/37a3820b067b06ff4904aa32251dbe71.png)
mouseenter()
当鼠标指针穿过元素时,会发生 mouseenter 事件。
mouseenter() 方法触发 mouseenter 事件,或规定当发生 mouseenter 事件时运行的函数:
![](https://i-blog.csdnimg.cn/blog_migrate/8a234cc43da2e5404cd8bb375cf74d6c.png)
mouseleave()
当鼠标指针离开元素时,会发生 mouseleave 事件。
mouseleave() 方法触发 mouseleave 事件,或规定当发生 mouseleave 事件时运行的函数:
![](https://i-blog.csdnimg.cn/blog_migrate/1f6f589f50a7b05c132b1c953bb9914a.png)
mousedown()
当鼠标指针移动到元素上方,并按下鼠标按键时,会发生 mousedown 事件。
mousedown() 方法触发 mousedown 事件,或规定当发生 mousedown 事件时运行的函数:
![](https://i-blog.csdnimg.cn/blog_migrate/ee3fa6abd3b394b68c62958d7a6b67d6.png)
mouseup()
当在元素上松开鼠标按钮时,会发生 mouseup 事件。
mouseup() 方法触发 mouseup 事件,或规定当发生 mouseup 事件时运行的函数:
![](https://i-blog.csdnimg.cn/blog_migrate/896f3040077c7ed49f83bc29502ef86e.png)
hover()
hover()方法用于模拟光标悬停事件。
当鼠标移动到元素上时,会触发指定的第一个函数(mouseenter);当鼠标移出这个元素时,会触发指定的第二个函数(mouseleave)。
![](https://i-blog.csdnimg.cn/blog_migrate/f27ab298647a8b47af54d2bce61b97aa.png)
focus()
当元素获得焦点时,发生 focus 事件。
当通过鼠标点击选中元素或通过 tab 键定位到元素时,该元素就会获得焦点。
focus() 方法触发 focus 事件,或规定当发生 focus 事件时运行的函数:
![](https://i-blog.csdnimg.cn/blog_migrate/652bfeeec1946b7ba3dd013330ac4a3a.png)
blur()
当元素失去焦点时,发生 blur 事件。
blur() 方法触发 blur 事件,或规定当发生 blur 事件时运行的函数:
![](https://i-blog.csdnimg.cn/blog_migrate/c11dbeff17e2e49254aecd3bf8fa9331.png)