JavaScript day-05
//demo1 javascript对象
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <script> //1.采用直接量方式创建对象 function f1(){ var student = { "name":"zhangsan","age":23,"work":function(){alert("I learn java.");} }; alert(student.name); alert(student.age); student.work(); } //2.采用内置构造器创建对象 function f2(){ var teacher = new Object(); teacher.name = "苍老师"; teacher.age = 18; teacher.work = function(){ alert("I teach java."); } alert(teacher.name); alert(teacher.age); teacher.work(); } //3.采用自定义构造器创建对象 function Coder(name,age,work){ this.name = name; this.age = age; //this指代当前对象 //.job是给此对象增加job属性 //=work是将参数work赋值给此属性 this.job = work; } function f3(){ var coder = new Coder("lisi",25,function(){ alert("I write java."); }); alert(coder.name); alert(coder.age); coder.job(); } </script> </head> <body> <input type="button" value="按钮1" onclick="f1();"/> <input type="button" value="按钮2" onclick="f2();"/> <input type="button" value="按钮3" onclick="f3();"/> </body> </html>
//demo2事件绑定方式
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <script> //直接定义事件 function f1(e){ console.log("aaa"); console.log(e); } //后绑定事件 window.onload = function(){ var btn = document.getElementById("btn2"); btn.onclick = function(e){ console.log("bbb"); console.log(e); } } </script> </head> <body> <input type="button" value="按钮1" onclick="f1(event);"/> <input id="btn2" type="button" value="按钮2"> </body> </html>
//demo3演示冒泡及获取事件源
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <style type="text/css"> div{ width:500px; border:1px solid red; padding:30px } p{ border:1px solid red; padding:30px } </style> <script> function f1(e){ alert("btn"); //停止冒泡 if(e.propagation){ e.propagation(); }else{ e.cancelBubble = true; } } function f2(e){ //获取事件源 var obj = e.srcElement || e.target; console.log(obj); } </script> </head> <body> <div onclick="alert('div');"> <p onclick="alert('p');"> <input type="button" value="按钮1" onclick="f1(event);"/> </p> </div> <div onclick="f2(event);"> <a href="#">顶部</a> <img style="width:218px;height:218px;" alt="" src="../images/IMG_20191112_235308.JPG"> <span>abc</span> </div> </body> </html>