Top

WebBasicJavaScriptUnit04

  1. 联动菜单
  2. 购物车
  3. 使用三种方式创建对象
  4. 计算器
  5. 事件的冒泡处理机制

1 联动菜单

1.1 问题

1)创建省、市下拉选

2)当改变省份时,重置市

1.2 方案

创建节点:document.createElement(elementName)

添加节点:parentNode.appendChild(newNode)

1.3 步骤

实现此案例需要按照如下步骤进行。

步骤一:创建HTML

在day07文件夹下创建demo1.html,代码如下:

<!DOCTYPE html>
<html>
  <head>
    <title>联动菜单</title>
    <meta charset="utf-8" />
    <script type="text/javascript">
      var province_cities = [
        ["请选择"],
        ["济南","青岛","烟台"],
        ["杭州","宁波","温州"],
        ["南京","无锡","苏州"]
      ];
      function change() {
        var p = document.getElementById("province");
        var cities = province_cities[p.value];
        var c = document.getElementById("city");
        c.innerHTML = "";
        for(var i=0;i<cities.length;i++) {
          var o = document.createElement("option");
          o.setAttribute("value",i);
          o.innerHTML = cities[i];
          c.appendChild(o);
        }
      }
    </script>
  </head>
  <body>
    <h1>联动菜单</h1>
    <p>
      <select id="province" onchange="change();">
        <option value="0">请选择</option>
        <option value="1">山东省</option>
        <option value="2">浙江省</option>
        <option value="3">江苏省</option>
      </select>
      <select id="city">
        <option value="0">请选择</option>
      </select>
    </p>
  </body>
</html>

步骤二:测试

使用浏览器打开demo1.html,选择一个省,效果如下图:

图-1

1.4 完整代码

demo1.html完整代码如下:

<!DOCTYPE html>
<html>
  <head>
    <title>联动菜单</title>
    <meta charset="utf-8" />
    <script type="text/javascript">
      var province_cities = [
        ["请选择"],
        ["济南","青岛","烟台"],
        ["杭州","宁波","温州"],
        ["南京","无锡","苏州"]
      ];
      function change() {
        var p = document.getElementById("province");
        var cities = province_cities[p.value];
        var c = document.getElementById("city");
        c.innerHTML = "";
        for(var i=0;i<cities.length;i++) {
          var o = document.createElement("option");
          o.setAttribute("value",i);
          o.innerHTML = cities[i];
          c.appendChild(o);
        }
      }
    </script>
  </head>
  <body>
    <h1>联动菜单</h1>
    <p>
      <select id="province" onchange="change();">
        <option value="0">请选择</option>
        <option value="1">山东省</option>
        <option value="2">浙江省</option>
        <option value="3">江苏省</option>
      </select>
      <select id="city">
        <option value="0">请选择</option>
      </select>
    </p>
  </body>
</html>

2 购物车

2.1 问题

1)修改购物数量后,计算金额

2)计算合计金额

2.2 方案

创建节点:document.createElement(elementName)

添加节点:parentNode.appendChild(newNode)

删除节点:node.removeChild(childNode)

2.3 步骤

实现此案例需要按照如下步骤进行。

步骤一:创建HTML

创建demo2.html,代码如下:

<!DOCTYPE html>
<html>
  <head>
    <title>购物车</title>
    <meta charset="utf-8" />
    <style type="text/css">
      h1 {
        text-align:center;
      }
      table {
        margin:0 auto;
        width:60%;
        border:2px solid #aaa;
        border-collapse:collapse;
      }
      table th, table td {
        border:2px solid #aaa;
        padding:5px;
      }
    </style>
    <script type="text/javascript">
      function add_shoppingcart(btn) {
        var tr = btn.parentNode.parentNode;
        var tds = tr.getElementsByTagName("td");
        var name = tds[0].innerHTML;
        var price = tds[1].innerHTML;
        
        var tbody = document.getElementById("goods");
        var row = tbody.insertRow();
        row.innerHTML = 
        	'<td>'+name+'</td>'+
            '<td>'+price+'</td>'+
            '<td align="center">'+
              '<input type="button" value="-" onclick="change(this, -1);"/> '+
              '<input type="text" size="3" readonly value="1"/> '+
              '<input type="button" value="+" onclick="change(this, 1);"/> '+
            '</td>'+
            '<td>'+price+'</td>'+
            '<td align="center"><input type="button" value="x" onclick="del(this);"/></td>';
        total();
      }
      
      function del(btn) {
        var tr = btn.parentNode.parentNode;
        tr.parentNode.removeChild(tr);
        total();
      }
      
      function total() {
         var tbody = document.getElementById("goods");
         var trs = tbody.getElementsByTagName("tr");
         var sum = 0;
         for(var i=0;i<trs.length;i++) {
           var td = trs[i].getElementsByTagName("td");
           var m = td[3].innerHTML;
           sum += parseFloat(m);
         }
         var total = document.getElementById("total");
         total.innerHTML = sum;
      }
      
      function change(btn, n) {
        var inputs = btn.parentNode.getElementsByTagName("input");
        var amount = parseInt(inputs[1].value);
        if(amount<=1 && n<0) {
          return;
        }
        
        inputs[1].value = amount + n;
        amount = inputs[1].value;
        
        var tr = btn.parentNode.parentNode;
        var tds = tr.getElementsByTagName("td");
        var price = parseFloat(tds[1].innerHTML);
        var m = price*amount;
        tds[3].innerHTML = m;
        
        total();
      }
    </script>
  </head>
  <body>
    <h1>真划算</h1>
    <table>
    <tr>
      <th>商品</th>
      <th>单价(元)</th>
      <th>颜色</th>
      <th>库存</th>
      <th>好评率</th>
      <th>操作</th>
    </tr>   
    <tr>
      <td>罗技M185鼠标</td>
      <td>80</td>
      <td>黑色</td>
      <td>893</td>
      <td>98%</td>
      <td align="center">
        <input type="button" value="加入购物车" onclick="add_shoppingcart(this);"/>
      </td>
    </tr>
    <tr>
      <td>微软X470键盘</td>
      <td>150</td>
      <td>黑色</td>
      <td>9028</td>
      <td>96%</td>
      <td align="center">
        <input type="button" value="加入购物车" onclick="add_shoppingcart(this);"/>
      </td>
    </tr>
    <tr>
      <td>洛克iphone6手机壳</td>
      <td>60</td>
      <td>透明</td>
      <td>672</td>
      <td>99%</td>
      <td align="center">
        <input type="button" value="加入购物车" onclick="add_shoppingcart(this);"/>
      </td>
    </tr>
    <tr>
      <td>蓝牙耳机</td>
      <td>100</td>
      <td>蓝色</td>
      <td>8937</td>
      <td>95%</td>
      <td align="center">
        <input type="button" value="加入购物车" onclick="add_shoppingcart(this);"/>
      </td>
    </tr>
    <tr>
      <td>金士顿U盘</td>
      <td>70</td>
      <td>红色</td>
      <td>482</td>
      <td>100%</td>
      <td align="center">
        <input type="button" value="加入购物车" onclick="add_shoppingcart(this);"/>
      </td>
    </tr>
    </table>
  
    <h1>购物车</h1>
    <table>
      <thead>
        <tr>
          <th>商品</th>
          <th>单价(元)</th>
          <th>数量</th>
          <th>金额(元)</th>
          <th>删除</th>
        </tr>
      </thead>
      <tbody id="goods">
        <!-- 
        <tr>
          <td>罗技M185鼠标</td>
          <td>80</td>
          <td align="center">
            <input type="button" value="-"/>
            <input type="text" size="3" readonly value="1"/>
            <input type="button" value="+"/>
          </td>
          <td>80</td>
          <td align="center"><input type="button" value="x"/></td>
        </tr>
        -->
      </tbody>
      <tfoot>
        <tr>
          <td colspan="3" align="right">总计</td>
          <td id="total"></td>
          <td></td>
        </tr>
      </tfoot>
    </table>    
  </body>
</html>

步骤二:测试

使用浏览器打开demo2.html,效果如下图:

图-2

2.4 完整代码

demo2.html完整代码如下:

<!DOCTYPE html>
<html>
  <head>
    <title>购物车</title>
    <meta charset="utf-8" />
    <style type="text/css">
      h1 {
        text-align:center;
      }
      table {
        margin:0 auto;
        width:60%;
        border:2px solid #aaa;
        border-collapse:collapse;
      }
      table th, table td {
        border:2px solid #aaa;
        padding:5px;
      }
    </style>
    <script type="text/javascript">
      function add_shoppingcart(btn) {
        var tr = btn.parentNode.parentNode;
        var tds = tr.getElementsByTagName("td");
        var name = tds[0].innerHTML;
        var price = tds[1].innerHTML;
        
        var tbody = document.getElementById("goods");
        var row = tbody.insertRow();
        row.innerHTML = 
        	'<td>'+name+'</td>'+
            '<td>'+price+'</td>'+
            '<td align="center">'+
              '<input type="button" value="-" onclick="change(this, -1);"/> '+
              '<input type="text" size="3" readonly value="1"/> '+
              '<input type="button" value="+" onclick="change(this, 1);"/> '+
            '</td>'+
            '<td>'+price+'</td>'+
            '<td align="center"><input type="button" value="x" onclick="del(this);"/></td>';
        total();
      }
      
      function del(btn) {
        var tr = btn.parentNode.parentNode;
        tr.parentNode.removeChild(tr);
        total();
      }
      
      function total() {
         var tbody = document.getElementById("goods");
         var trs = tbody.getElementsByTagName("tr");
         var sum = 0;
         for(var i=0;i<trs.length;i++) {
           var td = trs[i].getElementsByTagName("td");
           var m = td[3].innerHTML;
           sum += parseFloat(m);
         }
         var total = document.getElementById("total");
         total.innerHTML = sum;
      }
      
      function change(btn, n) {
        var inputs = btn.parentNode.getElementsByTagName("input");
        var amount = parseInt(inputs[1].value);
        if(amount<=1 && n<0) {
          return;
        }
        
        inputs[1].value = amount + n;
        amount = inputs[1].value;
        
        var tr = btn.parentNode.parentNode;
        var tds = tr.getElementsByTagName("td");
        var price = parseFloat(tds[1].innerHTML);
        var m = price*amount;
        tds[3].innerHTML = m;
        
        total();
      }
    </script>
  </head>
  <body>
    <h1>真划算</h1>
    <table>
    <tr>
      <th>商品</th>
      <th>单价(元)</th>
      <th>颜色</th>
      <th>库存</th>
      <th>好评率</th>
      <th>操作</th>
    </tr>   
    <tr>
      <td>罗技M185鼠标</td>
      <td>80</td>
      <td>黑色</td>
      <td>893</td>
      <td>98%</td>
      <td align="center">
        <input type="button" value="加入购物车" onclick="add_shoppingcart(this);"/>
      </td>
    </tr>
    <tr>
      <td>微软X470键盘</td>
      <td>150</td>
      <td>黑色</td>
      <td>9028</td>
      <td>96%</td>
      <td align="center">
        <input type="button" value="加入购物车" onclick="add_shoppingcart(this);"/>
      </td>
    </tr>
    <tr>
      <td>洛克iphone6手机壳</td>
      <td>60</td>
      <td>透明</td>
      <td>672</td>
      <td>99%</td>
      <td align="center">
        <input type="button" value="加入购物车" onclick="add_shoppingcart(this);"/>
      </td>
    </tr>
    <tr>
      <td>蓝牙耳机</td>
      <td>100</td>
      <td>蓝色</td>
      <td>8937</td>
      <td>95%</td>
      <td align="center">
        <input type="button" value="加入购物车" onclick="add_shoppingcart(this);"/>
      </td>
    </tr>
    <tr>
      <td>金士顿U盘</td>
      <td>70</td>
      <td>红色</td>
      <td>482</td>
      <td>100%</td>
      <td align="center">
        <input type="button" value="加入购物车" onclick="add_shoppingcart(this);"/>
      </td>
    </tr>
    </table>
  
    <h1>购物车</h1>
    <table>
      <thead>
        <tr>
          <th>商品</th>
          <th>单价(元)</th>
          <th>数量</th>
          <th>金额(元)</th>
          <th>删除</th>
        </tr>
      </thead>
      <tbody id="goods">
        <!-- 
        <tr>
          <td>罗技M185鼠标</td>
          <td>80</td>
          <td align="center">
            <input type="button" value="-"/>
            <input type="text" size="3" readonly value="1"/>
            <input type="button" value="+"/>
          </td>
          <td>80</td>
          <td align="center"><input type="button" value="x"/></td>
        </tr>
        -->
      </tbody>
      <tfoot>
        <tr>
          <td colspan="3" align="right">总计</td>
          <td id="total"></td>
          <td></td>
        </tr>
      </tfoot>
    </table>    
  </body>
</html>

3 使用三种方式创建对象

3.1 问题

1)直接创建对象

2)使用构造器创建对象

3)使用JSON创建对象

3.2 方案

对象的创建方式:

1)直接创建对象

2)使用构造器创建对象

3)使用JSON创建对象

3.3 步骤

实现此案例需要按照如下步骤进行。

步骤一:创建HTML

创建demo3.html,代码如下:

<!DOCTYPE html>
<html>
  <head>
    <title>创建对象</title>
    <meta charset="utf-8" />
    <script type="text/javascript">
      function f1() {
        var teacher = new Object();
        teacher.name = "苍老师";
        teacher.age = "40";
        teacher.work = function() {
          alert("我教Java");
        };
        
        alert(teacher.name);
        alert(teacher.age);
        teacher.work();
      }
      function f2() {
        var s = new Student("张三", 22);
        alert(s.name);
        alert(s.age);
        s.work();
      }
      function Student(name, age) {
        this.name = name;
        this.age = age;
        this.work = function() {
          alert("我学Java");
        };
      }
      function f3() {
        var programmer = {"name":"李四", "age":30, 
          "work":function(){alert("我写Java代码")}};
        alert(programmer.name);
        alert(programmer.age);
        programmer.work();
      }
    </script>
  </head>
  <body>
    <h1>创建对象</h1>
    <p>
      <input type="button" value="创建通用对象" onclick="f1();"/>
      <input type="button" value="创建对象模板" onclick="f2();"/>
      <input type="button" value="创建JSON对象" onclick="f3();"/>
    </p>
  </body>
</html>

步骤二:测试

使用浏览器打开demo3.html,效果如下图:

图-3

3.4 完整代码

demo3.html完整代码如下:

<!DOCTYPE html>
<html>
  <head>
    <title>创建对象</title>
    <meta charset="utf-8" />
    <script type="text/javascript">
      function f1() {
        var teacher = new Object();
        teacher.name = "苍老师";
        teacher.age = "40";
        teacher.work = function() {
          alert("我教Java");
        };
        
        alert(teacher.name);
        alert(teacher.age);
        teacher.work();
      }
      function f2() {
        var s = new Student("张三", 22);
        alert(s.name);
        alert(s.age);
        s.work();
      }
      function Student(name, age) {
        this.name = name;
        this.age = age;
        this.work = function() {
          alert("我学Java");
        };
      }
      function f3() {
        var programmer = {"name":"李四", "age":30, 
          "work":function(){alert("我写Java代码")}};
        alert(programmer.name);
        alert(programmer.age);
        programmer.work();
      }
    </script>
  </head>
  <body>
    <h1>创建对象</h1>
    <p>
      <input type="button" value="创建通用对象" onclick="f1();"/>
      <input type="button" value="创建对象模板" onclick="f2();"/>
      <input type="button" value="创建JSON对象" onclick="f3();"/>
    </p>
  </body>
</html>

4 计算器

4.1 问题

1)做一个完整的计算器

2)使用 event 对象简化简单计算器的界面设计及实现

4.2 方案

使用event对象:

var obj = e.srcElement || e.target;

4.3 步骤

实现此案例需要按照如下步骤进行。

步骤一:创建HTML

创建demo4.html,代码如下:

<!DOCTYPE html>
<html>
  <head>
    <title>计算器</title>
    <meta charset="utf-8" />
    <style type="text/css">
      .panel {
        border: 4px solid #ddd;
        width: 192px;
        margin: 100px auto;
        /*border-radius: 6px;*/
      }
      .panel p, .panel input {
        font-family: "微软雅黑";
        font-size: 20px;
        margin: 4px;
        float: left;
        /*border-radius: 4px;*/
      }
      .panel p {
        width: 122px;
        height: 26px;
        border: 1px solid #ddd;
        padding: 6px;
        overflow: hidden;
      }
      .panel input {
        width: 40px;
        height: 40px;
        border:1px solid #ddd;
      }
    </style>
    <script type="text/javascript">
      function cal(e) {
        var obj = e.target || e.srcElement;
        if(obj.nodeName != "INPUT") {
          return;
        }
        
        var value = obj.value;
        var screen = document.getElementById("screen");
        if(value=="C") {
          screen.innerHTML = "";
        } else if (value=="=") {
          var exp = screen.innerHTML;
          try {
            var r = eval("("+exp+")");
            screen.innerHTML = r;
          } catch(e) {
            console.log(e);
            screen.innerHTML = "Error";
          }
        } else {
          screen.innerHTML += value;
        }
      }
    </script>
  </head>
  <body>
    <div class="panel" onclick="cal(event);">
      <div>
        <p id="screen"></p>
        <input type="button" value="C">
        <div style="clear:both"></div>
      </div>
      <div>
        <input type="button" value="7">
        <input type="button" value="8">
        <input type="button" value="9">
        <input type="button" value="/">
        
        <input type="button" value="4">
        <input type="button" value="5">
        <input type="button" value="6">
        <input type="button" value="*">
        
        <input type="button" value="1">
        <input type="button" value="2">
        <input type="button" value="3">
        <input type="button" value="-">
        
        <input type="button" value="0">
        <input type="button" value=".">
        <input type="button" value="=">
        <input type="button" value="+">
        
        <div style="clear:both"></div>
      </div>
    </div>    
  </body>
</html>

步骤二:测试

使用浏览器打开demo4.html,效果如下图:

图-4

4.4 完整代码

demo4.html完整代码如下:

<!DOCTYPE html>
<html>
  <head>
    <title>计算器</title>
    <meta charset="utf-8" />
    <style type="text/css">
      .panel {
        border: 4px solid #ddd;
        width: 192px;
        margin: 100px auto;
        /*border-radius: 6px;*/
      }
      .panel p, .panel input {
        font-family: "微软雅黑";
        font-size: 20px;
        margin: 4px;
        float: left;
        /*border-radius: 4px;*/
      }
      .panel p {
        width: 122px;
        height: 26px;
        border: 1px solid #ddd;
        padding: 6px;
        overflow: hidden;
      }
      .panel input {
        width: 40px;
        height: 40px;
        border:1px solid #ddd;
      }
    </style>
    <script type="text/javascript">
      function cal(e) {
        var obj = e.target || e.srcElement;
        if(obj.nodeName != "INPUT") {
          return;
        }
        
        var value = obj.value;
        var screen = document.getElementById("screen");
        if(value=="C") {
          screen.innerHTML = "";
        } else if (value=="=") {
          var exp = screen.innerHTML;
          try {
            var r = eval("("+exp+")");
            screen.innerHTML = r;
          } catch(e) {
            console.log(e);
            screen.innerHTML = "Error";
          }
        } else {
          screen.innerHTML += value;
        }
      }
    </script>
  </head>
  <body>
    <div class="panel" onclick="cal(event);">
      <div>
        <p id="screen"></p>
        <input type="button" value="C">
        <div style="clear:both"></div>
      </div>
      <div>
        <input type="button" value="7">
        <input type="button" value="8">
        <input type="button" value="9">
        <input type="button" value="/">
        
        <input type="button" value="4">
        <input type="button" value="5">
        <input type="button" value="6">
        <input type="button" value="*">
        
        <input type="button" value="1">
        <input type="button" value="2">
        <input type="button" value="3">
        <input type="button" value="-">
        
        <input type="button" value="0">
        <input type="button" value=".">
        <input type="button" value="=">
        <input type="button" value="+">
        
        <div style="clear:both"></div>
      </div>
    </div>    
  </body>
</html>

5 事件的冒泡处理机制

5.1 问题

1)体验事件的冒泡处理机制

2)取消事件冒泡

5.2 方案

取消事件冒泡:

event.stopPropagation();

event.cancelBubble = true;

5.3 步骤

实现此案例需要按照如下步骤进行。

步骤一:创建HTML

创建demo5.html,代码如下:

<!DOCTYPE html>
<html>
  <head>
    <title>事件冒泡</title>
    <meta charset="utf-8" />
    <style type="text/css">
      div {
        border:1px solid #ccc;
        margin:10px;
        padding:20px;
      }
      #d1 {
        width:300px;
        height:300px;
        background-color: red;
      }
      #d2 {
        width:200px;
        height:200px;
        background-color: blue;
      }
      #d3 {
        width:100px;
        height:100px;
        background-color: yellow;
      }
    </style>
    <script type="text/javascript">
      function f1() {
        alert("d1");
      }
      function f2() {
        alert("d2");
      }
      function f3(e) {
        alert("d3");
        if(e.stopPropagation) {
          e.stopPropagation();
        } else {
          e.cancelBuddle();
        }
      }
    </script>
  </head>
  <body>
    <h1>事件冒泡</h1>
    <div id="d1" onclick="f1();">
      d1
      <div id="d2" onclick="f2();">
        d2
        <div id="d3" onclick="f3(event);">
          d3
        </div>
      </div>
    </div>
  </body>
</html>

步骤二:测试

使用浏览器打开demo5.html,效果如下图:

图-5

5.4 完整代码

demo5.html完整代码如下:

<!DOCTYPE html>
<html>
  <head>
    <title>事件冒泡</title>
    <meta charset="utf-8" />
    <style type="text/css">
      div {
        border:1px solid #ccc;
        margin:10px;
        padding:20px;
      }
      #d1 {
        width:300px;
        height:300px;
        background-color: red;
      }
      #d2 {
        width:200px;
        height:200px;
        background-color: blue;
      }
      #d3 {
        width:100px;
        height:100px;
        background-color: yellow;
      }
    </style>
    <script type="text/javascript">
      function f1() {
        alert("d1");
      }
      function f2() {
        alert("d2");
      }
      function f3(e) {
        alert("d3");
        if(e.stopPropagation) {
          e.stopPropagation();
        } else {
          e.cancelBuddle();
        }
      }
    </script>
  </head>
  <body>
    <h1>事件冒泡</h1>
    <div id="d1" onclick="f1();">
      d1
      <div id="d2" onclick="f2();">
        d2
        <div id="d3" onclick="f3(event);">
          d3
        </div>
      </div>
    </div>
  </body>
</html>