有两种绑定事件方式
eventName(fn)编码效率略高/ 部分事件jQuery没有实现,所以不能添加
$(function () { $("button").click(function () { alert("hello lnj") }) $("button").click(function () { alert("hello 123") }) $("button").mouseleave(function () { alert("hello mouseleave") }) $("button").mouseenter(function () { alert("hello mouseenter") }) }) on(eventName, fn)编码效率略低/ 所有js事件都可以添加
可以添加多个相同或者不同类型的事件,不会覆盖
$(function () { $("button").on("click", function () { alert("hello click1") }) $("button").on("click", function () { alert("hello click2") }) $("button").on("mouseleave", function () { alert("hello mouseleave") }) $("button").on("mouseenter", function () { alert("hello mouseenter") }) })满足条件
事件必须是通过on绑定的事件必须通过trigger来触发 $(function () { $(".son").on("myClick", function () { alert("son") }) $(".son").triggerHandler("myClick") })满足条件
事件是通过on来绑定的通过trigger触发事件 $(function () { $(".son").on("click.zs", function () { alert("click1") }) $(".son").on("click.ls", function () { alert("click2") }) // $(".son").trigger("click.zs") $(".son").trigger("click.ls") })请别人帮忙做事情, 然后将做完的结果反馈给我们
在jQuery中,如果通过核心函数找到的元素不止一个, 那么在添加事件的时候,jQuery会遍历所有找到的元素,给所有找到的元素添加事件
$(function () { $(".son").on("click.zs", function () { alert("click1") }) $(".son").on("click.ls", function () { alert("click2") }) // $(".son").trigger("click.zs") $(".son").trigger("click.ls") })事件委托练习
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> *{ margin: 0; padding: 0; } html,body{ width: 100%; height: 100%; } .mask{ width: 100%; height: 100%; background: rgba(0,0,0,0.5); position: fixed; top: 0; left: 0; } .login{ width: 521px; height: 292px; margin: 100px auto; position: relative; } .login>span{ width: 50px; height: 50px; /*background: red;*/ position: absolute; top: 0; right: 0; } </style> <script src="js/jquery-1.12.4.js"></script> <script> $(function () { // 编写jQuery相关代码 $("a").click(function () { var $mask = $("<div class=\"mask\">\n" + " <div class=\"login\">\n" + " <img src=\"images/login.png\" alt=\"\">\n" + " <span></span>\n" + " </div>\n" + "</div>") // 添加蒙版 $("body").append($mask); $("body").delegate(".login>span", "click", function () { // 移除蒙版 $mask.remove() }) return false }) }) </script> </head> <body> <!-- <div class="mask"> <div class="login"> <images src="images/login.png" alt=""> <span></span> </div> </div> --> <a href="http://www.baidu.com">点击登录</a> <div><img src="images/06.gif" width="100%" height="100%"></div> </body> </html>