jQuery事件相关

来源:互联网 发布:java web尚学堂 编辑:程序博客网 时间:2024/06/03 18:37
 <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>事件相关</title> <script type="text/javascript" src="../jquery-2.2.3.js"></script> <style type="text/css"> .div_1{ width: 300px; height: 300px; }   .div_2{ background: red; } </style> </head> <body>   <div class="div_1">   </div>   <input type="button" value="按钮1" /> <input type="button" value="按钮2" />   <script type="text/javascript"> //DOM加载完毕后调用 $(function () { //添加单机事件 // $('[value = 按钮1]').click(function () { // console.log($(this).val()); // });   //hover事件 可以接受两个参数,分别是事件触发函数 // $('[value = 按钮1]').hover(function () { // $(this).addClass("div_2"); // }, function () { // $(this).removeClass("div_2"); // });   //hover事件 接受一个参数的话 $('.div_1').hover(function () { $(this).toggleClass("div_2"); });   /* on: 是jQuery事件的统一接口,on方法可以接受2个参数 参数1:要绑定的事件类型,也可以同时绑定多个事件 参数2:事件回调函数 */ //一个事件 // $('[value = 按钮2]').on('click', function () { // console.log($(this).val()); // });   //同时绑定2个事件 $('[value = 按钮2]').on('click mouseover', function (e) { //e 形参:就是event对象 if (e.type == 'click') { console.log(e.type); //事件类型 console.log(e.target); //事件源 console.log(e.pageX); //触发事件的x轴坐标 console.log(e.pageY); //触发事件的y轴坐标 console.log("单机单机!!!"); $(this).removeClass("div_2"); } else { $(this).addClass("div_2"); } });   //off:移除事件 // $('[value = 按钮2]').off('click mouseover');   //one: 只触发一次的事件 //注意:之前如果绑定其他的click事件后,不影响其他的click事件 $('[value = 按钮1]').one('click', function () { console.log("只触发一次!!!!"); });   //each:遍历 //注意:和forEach不要弄混淆 //匿名函数的第一个参数是:下标, 第二个参数是:元素 $('[type = button]').each(function (idx, ele) { console.log(idx); console.log($(this).val()); console.log($(ele).val()); console.log(ele.value); console.log(this.value); });   }); </script> </body> </html>
0 0