Skip to content

Javascript基础

1 实验类型

验证型,2学时,必选实验

2 实验目的

掌握Javascript基础语法;熟悉JavaScript编写简单的Web应用程序

3 实验要求

验证参考代码;修改参考代码,实现自己的设计;将关键结果截图及源代码整理成实验报告

4 实验环境

Windows7、Microsoft Edge/Chrome/Firefox等浏览器、Visual Studio Code(VS Code)

5 实验步骤

创建工作目录:{盘符}:/{学号}/exp2_3, 后续文件均存放在工作目录

变量

编写Javascript代码,定义并使用变量,理解变量作用域的概念。

创建文件:js_var.html,调试以下代码,观察并解释窗口中显示的结果:

变量
<script language="javascript">
  var x = 13, y = 29;
  function test() {
    var num, y = 10;
    num = x + y;
    x++
    document.write("内部的num的值为:" + num + "<br>");
  }
  test();
  document.write("测试x的值为:" + x + "<br>");
  document.write("测试y的值为:" + y + "<br>");
  document.write("外部的num的值为:" + num + "<br>");
</script>

数组与循环

创建文件:js_array.html,使用数组存储一周的星期名称,使用数组遍历的方式输出数组中的内容,参考代码:

数组与循环
1
2
3
4
5
6
7
8
9
<script>
  // 定义一个数组,存储一周的星期名称
  var weekDays = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"];

  // 使用for循环遍历数组并输出每个元素
  for (var i = 0; i < weekDays.length; i++) {
    console.log(weekDays[i]);
  }
</script>

控制语句与函数

创建文件:js_if.html,通过分支控制语句及函数调用实现以下功能:根据时间段的不同,在网页中显示不同的问候语,12点以前,则输出“早上好!”的问候语,颜色为绿色;12点至18点,则输出“下午好!”颜色为黄色;18点以后输出“晚上好!”颜色为黑色。

参考代码:

控制语句与函数
<script language="javascript">
  var curday = new Date();
  hours = curday.getHours();
  document.write("现在是:" + hours + "点,");
  if (hours <= 12) {
    document.write("<font color='00ff00'>早上好!</font>");
  } else if (hours <= 18) {
    document.write("<font color='ffff00'>中午好!</font>");
  } else {
    document.write("<font color='000000'>晚上好!</font>");
  }
</script>

事件处理

创建文件:js_event.html,处理Html元素(如按钮,文本框)的常见事件,如下表:

元素类型 事件类型 事件处理函数
<button> mousedown handleMouseDown()
<button> mouseup handleMouseUp()
<button> mouseover handleMouseOver()
<button> mouseout handleMouseOut()
<button> click handleClick()
<input> focus handleFocus()
<input> blur handleBlur()

参考代码:

事件处理
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">

  <script>
    // 定义事件处理函数  
    function handleClick() {
      var message = document.getElementById('message');
      message.textContent = '你点击了按钮!';
    }

    function handleMouseDown() {
      var button = document.getElementById('myButton');
      button.classList.add('active');
      var message = document.getElementById('message');
      message.textContent = '鼠标按下了按钮!';
    }

    function handleMouseUp() {
      var button = document.getElementById('myButton');
      button.classList.remove('active');
      var message = document.getElementById('message');
      message.textContent = '鼠标松开了按钮!';
    }

    function handleMouseOver() {
      var button = document.getElementById('myButton');
      button.classList.add('active');
      var message = document.getElementById('message');
      message.textContent = '鼠标悬停在按钮上!';
    }

    function handleMouseOut() {
      var button = document.getElementById('myButton');
      button.classList.remove('active');
      var message = document.getElementById('message');
      message.textContent = '鼠标离开了按钮!';
    }

    function handleFocus() {
      var input = document.getElementById('myInput');
      input.style.borderColor = 'blue'; // 当输入框获得焦点时,改变边框颜色  
      var message = document.getElementById('message');
      message.textContent = '输入框获得了焦点!';
    }

    function handleBlur() {
      var input = document.getElementById('myInput');
      input.style.borderColor = ''; // 当输入框失去焦点时,移除边框颜色  
      var message = document.getElementById('message');
      message.textContent = '输入框失去了焦点!';
    }  
  </script>
</head>

<body>
  <button id="myButton" onmousedown="handleMouseDown()" onmouseup="handleMouseUp()" onmouseover="handleMouseOver()"
    onmouseout="handleMouseOut()" onclick="handleClick()">点击我</button>

  <input type="text" id="myInput" placeholder="输入文本" onfocus="handleFocus()" onblur="handleBlur()">
  <p id="message">你还没有进行任何操作。</p>
</body>

</html>

JSON

创建文件:js_event.html,使用JSON数组存放学生信息:学号、姓名、年龄,在界面中显示学生信息,参考代码:

JSON
<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
</head>

<body>
  <h1>学生信息</h1>
  <table id="studentTable" border="1">
    <thead>
      <tr>
        <th>学号</th>
        <th>姓名</th>
        <th>年龄</th>
      </tr>
    </thead>
    <tbody>
      <!-- 这里将通过JavaScript动态插入学生信息 -->
    </tbody>
  </table>

  <script>
    // 假设这是从服务器获取的JSON数据
    var studentData = [
      { "学号": "20210001", "姓名": "张三", "年龄": 20 },
      { "学号": "20210002", "姓名": "李四", "年龄": 21 },
      { "学号": "20210003", "姓名": "王五", "年龄": 22 }
    ];

    // 获取表格的tbody元素
    var tbody = document.getElementById('studentTable').getElementsByTagName('tbody')[0];

    // 遍历JSON数据并创建表格行
    studentData.forEach(function (student) {
      var row = tbody.insertRow();
      var cell1 = row.insertCell(0);
      var cell2 = row.insertCell(1);
      var cell3 = row.insertCell(2);
      cell1.innerHTML = student["学号"];
      cell2.innerHTML = student["姓名"];
      cell3.innerHTML = student["年龄"];
    });
  </script>
</body>

</html>

综合

弹出框

创建文件:js_comprehensive.html,使用Html+css+js实现一个可关闭的弹出框,参考代码如下:

弹出框
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
</head>

<head>
  <script>
    function init() {
      // 获取弹窗
      var modal = document.getElementById('myModal');

      // 打开弹窗的按钮对象
      var btn = document.getElementById("myBtn");

      // 获取 <span> 元素,用于关闭弹窗
      var span = document.querySelector('.close');

      // 点击按钮打开弹窗
      btn.onclick = function () {
        modal.style.display = "block";
      }

      // 点击 <span> (x), 关闭弹窗
      span.onclick = function () {
        modal.style.display = "none";
      }

      // 在用户点击其他地方时,关闭弹窗
      window.onclick = function (event) {
        if (event.target == modal) {
          modal.style.display = "none";
        }
      }
    }

  </script>
  <style>
    /* 弹窗 (background) */
    .modal {
      display: none;
      /* 默认隐藏 */
      position: fixed;
      /* 固定定位 */
      z-index: 1;
      /* 设置在顶层 */
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      overflow: auto;
      background-color: rgb(0, 0, 0);
      background-color: rgba(0, 0, 0, 0.4);
    }

    /* 弹窗内容 */
    .modal-content {
      background-color: #fefefe;
      margin: 15% auto;
      padding: 20px;
      border: 1px solid #888;
      width: 80%;
    }

    /* 关闭按钮 */
    .close {
      color: #aaa;
      float: right;
      font-size: 28px;
      font-weight: bold;
    }

    .close:hover,
    .close:focus {
      color: black;
      text-decoration: none;
      cursor: pointer;
    }
  </style>
</head>

<body onload="init()">
  <!-- 打开弹窗按钮 -->
  <button id="myBtn">打开弹窗</button>

  <!-- 弹窗 -->
  <div id="myModal" class="modal">

    <!-- 弹窗内容 -->
    <div class="modal-content">
      <span class="close">&times;</span>
      <p>弹窗中的文本...</p>
    </div>

  </div>

</body>

</html>

表单校验

创建文件:js_validation.html,使用Javascript对Html基础实验中创建的学生表的表单数据进行校验,至少实现以下规则:

元素 校验规则
学号 (no) - 不能为空
- 必须是数字
姓名 (name) - 不能为空
性别 (gender) - 必须是"男"或"女"
年龄 (age) - 不能为空
- 必须是正整数
所在系 (dept) - 不能为空

代码模板如下:

表单校验
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>学生表</title>
  <script>
    function validateForm() {
      var no = document.forms["studentForm"]["no"].value;

      if (no == "") {
        alert("学号不能为空");
        return false;
      }

      //完成后续校验
    }  
  </script>
</head>

<body>
  <h3>学生表</h3>
  <div class="container">
    <form name="studentForm" onsubmit="return validateForm()" action="#">
      <div>
        <label for="no">学号:</label>
        <input type="text" id="no" name="no" placeholder="请输入学号..">
      </div>

      <!-- 完整代码参考html部分实验 -->      
      <button type="submit">提交</button>
    </form>
  </div>
</body>

</html>

拓展练习

  1. 使用JSON数组存放学生信息:学号、姓名、年龄,编写代码计算学生的最高、最低、平均年龄以及标准差

    参考JSON步骤

  2. 为课程表表单界面增加校验功能,至少实现4种规则的校验

    参考表单校验步骤