JavaWeb10.1【JS:DOM入门、事件绑定入门、案例1电灯开关】
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 7 <script> 8 //通过id获取元素对象 9 // var light = document.getElementById("light"); 10 // alert(light); //null js在此处获取不到下面还未执行的内容,所以要将js定义在所需内容的下面,推荐放在body最下方 11 </script> 12 </head> 13 <body> 14 <img id="light" src="../img/off.gif"> 15 <h1 id="title">悔创阿里杰克马</h1> 16 17 <script> 18 //通过id获取元素对象 19 var light = document.getElementById("light"); 20 // alert(light); 21 alert("我要换图片了。。。"); 22 light.src = "../img/on.gif"; 23 24 //1.获取h1标签对象 25 var title = document.getElementById("title"); 26 alert("我要换内容了。。。"); 27 //2.修改内容 28 title.innerHTML = "不识妻美刘强东"; 29 </script> 30 </body> 31 </html>
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 7 <script> 8 function fun() { 9 alert("我被点了"); 10 } 11 </script> 12 </head> 13 <body> 14 <!--<img id="light" src="../img/off.gif" onclick="alert('我被点了')">--> 15 <img id="light" src="../img/off.gif" onclick="fun()"> <!--方式1--> 16 <img id="light2" src="../img/off.gif" > 17 18 <script> 19 function fun2() { 20 alert("咋老点我"); 21 } 22 /*方式2*/ 23 //1 获取light2对象 24 var light2 = document.getElementById("light2"); 25 //2 绑定事件 26 light2.onclick = fun2; 27 </script> 28 </body> 29 </html>
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body> 8 <img src="../img/off.gif" id="light"> 9 10 /* 11 分析: 12 1.获取图片对象 13 2.绑定单击事件 14 3.每次点击切换图片 15 * 规则: 16 * 如果灯是开的 on,切换图片为 off 17 * 如果灯是关的 off,切换图片为 on 18 * 使用标记flag来完成 19 20 */ 21 22 <script> 23 var light = document.getElementById("light"); 24 var flag = false; //代表灯灭状态off 25 light.onclick = function(){ //匿名方法 26 if (flag){ 27 light.src = "../img/on.gif"; 28 flag = false; 29 } else { 30 light.src = "../img/off.gif"; 31 flag = true; 32 } 33 } 34 </script> 35 </body> 36 </html>