jQuery能够为一个元素注册多个相同事件处理函数
分类:实例代码
显然这是jquery能够实现的,只要是原生javascript实现的功能,jquery自然都能够实现,因为jquery就是由原生javascript编写而成。
但是不少初学者如果注意不够的话,可能会犯一些错误,这主要是由于使用句柄方式注册事件处理函数的习惯导致的。
代码实例如下:
<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <meta name="author" content="http://www.pipipi.net/" /> <title>前端教程网</title> <style type="text/css"> #antzone { height: 30px; width: 100px; background: #ccc; text-align:center; line-height:30px; } </style> <script type="text/javascript"> window.onload = function () { var obt = document.getElementById("bt"); var odiv = document.getElementById("antzone"); obt.onclick = function () { odiv.innerHTML = "前端教程网"; } obt.onclick = function () { odiv.style.backgroundColor = "blue"; } } </script> </head> <body> <div id="antzone"></div> <input type="button" id="bt" value="查看效果" /> </body> </html>
通过句柄方式注册事件处理函数,后面的会覆盖掉前面,所以只能够设置div的背景色为蓝色。
更多原生javascript注册事件处理函数的方式可以参阅javascript如何注册事件处理函数一章节。
使用jquery注册事件处理函数就不用担心被覆盖的问题,代码实例如下:
<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <meta name="author" content="http://www.pipipi.net/" /> <title>前端教程网</title> <style type="text/css"> #antzone { height: 30px; width: 100px; background: #ccc; text-align:center; line-height:30px; } </style> <script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script> <script type="text/javascript"> $(document).ready(function () { $("#bt").click(function () { $("#antzone").text("前端教程网"); }); $("#bt").click(function () { $("#antzone").css("background-color","blue"); }); }) </script> </head> <body> <div id="antzone"></div> <input type="button" id="bt" value="查看效果" /> </body> </html>
上面两个事件处理函数都得到了良好的执行。
一线大厂高级前端编写,前端初中阶面试题,帮助初学者应聘,需要联系微信:javadudu