事件处理on绑定—个或者多个事件
单个事件注册
语法:
element.事件(function () {})
$ ( "div" ) .click ( function (){事件处理程序})
其他事件基本和原生一致
比如mouseover、mouseout、blur、focus、change、keydown、keyup、resize、scroll等
示例代码:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>01-事件处理on</title> <style type="text/css"> div { width: 100px; height: 100px; background-color: pink; } .current{ background-color: purple; } </style> <script src="jquery-3.6.0.js" type="text/javascript" charset="utf-8"></script> </head> <body> <div></div> <ul> <li>222</li> <li>222</li> <li>222</li> <li>222</li> <li>222</li> <li>222</li> <li>222</li> </ul> <ol> </ol> </body> <script type="text/javascript"> $(function() { //1.单个事件注册 // $("div").click(function(){ // $(this).css("background","purple") // }) // $("div").mouseenter(function(){ // $(this).css("background","skyblue") // }) //2.事件处理on // $("div").on({ // mouseenter: function() { // $(this).css("background", "skyblue") // }, // click: function() { // $(this).css("background", "yellow") // }, // mouseleave: function() { // $(this).css("background", "blue") // } // }); $("div").on("mouseenter mouseleave",function(){ $(this).toggleClass("current"); }) // (2) on可以实现事件委托(委派) // $("ul li").click() $("ul").on("click","li",function(){ alert(111) }); // click是绑定在ul身上的,但是触发的对象是ul里面的小li //(3)on可以给动态创建的元素绑定事件 // $("ol li").click(function(){ // alert(11); // }) $("ol").on("click","li",function(){ alert(11) }) var li = $("<li>我是后来创建的</li>") $("ol").append(li) }) </script> </html>