javaScripe:负责网页的行为。

javaScripe_html

与Java不同的是,它不需要编译。

1.js引入方式


javaScripe_JSON_02

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JS-引入方式</title>
    <!-- 内部脚本 -->
    <!--
    <script>
        alert('Hello JS');
    </script>
    -->
    <!-- 外部脚本 -->
    <script src="js/demo.js"></script>
</head>
<body>

</body>
</html>

2.js基础语法

书写语法

书写语法

javaScripe_字符串_03

输出语句

javaScripe_JSON_04

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JS-基本语法</title>
</head>
<body>

<script>
    /* alert("JS"); */

    // 方式一: 弹出警告框
    window.alert("hello js");

    // 方式二: 写入html页面中
    document.write("hello js");

    // 方式三: 控制台输出
    console.log("hello js");
</script>

</body>
</html>

变量

javaScripe_html_05

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>变量示例</title>
</head>
<body>

<script>
    // var: 作用域比较大,全局变量
    // 可以重复定义
    var a = 1;
    alert(a);

    // var特点 1:作用域较大,全局变量
    //  var特点 2: 可以重复定义
    {
        var x = 1;
        var x = "A";
    }
    alert(x);

    // let: 局部变量;不能重复定义
    {
        let x = 1;
        alert(x);
    }

    // const: 常量,不能给改变的。
    const pi = 3.14;
    // pi = 3.15; // 这一行会导致错误,因为常量不能被重新赋值
    alert(pi);
</script>

</body>
</html>

数据类型、运算符、流程控制语句

javaScripe_字符串_06

<script>
    // 原始数据类型

    alert(typeof 3);         // number
    alert(typeof 3.14);      // number

    alert(typeof "A");       // string
    alert(typeof 'Hello');   // string

    alert(typeof true);      // boolean
    alert(typeof false);     // boolean

    alert(typeof null);      // object (这是JavaScript语言的一个历史遗留问题)

    var a;
    alert(typeof a);         // undefined
</script>

javaScripe_html_07

这些运算符大部分与Java相同。

javaScripe_html_08

<script>
        var age = 20;
        var _age = "20";
        var $age = 20;
    
        // 比较操作
        alert(age == _age);   // true,值相等
        alert(age === _age);  // false,类型不相等
        alert(age === $age);  // true,值和类型都相等
    
        // 类型转换 - 其他类型转为数字
        alert(parseInt("12"));     // 12
        alert(parseInt("12A45"));  // 12,遇到非数字字符时停止解析
        alert(parseInt("A45"));    // NaN,不是数字

        // 类型转换 - 数字转为其他类型
        alert(String(12));     // "12"
        alert(Number("12"));    // 12
        alert(Boolean(12));    // true
        alert(Boolean(0));     // false

         // 类型转换 - 其他类型转为boolean
        if (0) {
            alert("0 转换为 false");// 失败
        }
        
        if (NaN) {
            alert("NaN 转换为 false");// 失败
        }
        
        if (1) {
            alert("除 0 和 NaN 其他数字都转换为 true");
        }
        
        if ("") {
            alert("空字符串为 false,其他都是 true");// 失败
        }
        
        if (null) {
            alert("null 转化为 false");// 失败
        }

        if (undefined) {
            alert("undefined 转化为 false");// 失败
        }
    </script>

其他类型转为布尔,只有0、NaN、空字符、null、undefined转换为false

javaScripe_html_09

流程控制与Java相同。

3.js函数

javaScripe_html_10

js比Java宽松许多...

形参和返回值不需要定义。第二种方法更常用。

函数调用时可以传输多个参数,但是只会用定义好的个数

<script>
        // 定义函数-1
        // function add(a, b) {
        //     return a + b;
        // }

        // 定义函数-2
        var add = function(a, b) {
            return a + b;
        };

        // 函数调用
        var result = add(10, 20);
        var result = add(10, 20,30,40);只用前两个
        alert(result);

    </script>

4.JS对象

Array

javaScripe_html_11

js中的数组相当于Java中的集合,数组的长度和类型都是可变的。

<script>
    // 定义数组
    // var arr = new Array(1, 2, 3, 4);
    // var arr = [1, 2, 3, 4];

    // 示例操作
    var arr = [1, 2, 3, 4];
    arr[10] = 50;  // 将第11个位置设为50,数组长度变为11

    console.log(arr[10]);  // 输出 50
    console.log(arr[9]);   // 输出 undefined,位置9没有元素
    console.log(arr[8]);   // 输出 undefined,位置8没有元素

    arr[9] = "A";  // 将位置9设为字符串 "A"
    arr[8] = true; // 将位置8设为布尔值 true

    console.log(arr); // 输出完整数数组后,输出完整的数组:[1, 2, 3, 4, <4 empty items>, true, "A", 50]

    </script>

javaScripe_JSON_12

for循环和forEach不同。前者全都遍历,后者只遍历有值的。

<script>
    var arr = [1, 2, 3, 4];
    arr[10] = 50;

    // 传统for循环遍历数组
    for (let i = 0; i < arr.length; i++) {
        console.log(arr[i]);
    }

    console.log("===================");

    // forEach: 遍历数组中有值的元素
    arr.forEach(function (e) {
        console.log(e);
    });

    // ES6 箭头函数。forEach的简写,类似Java的lambda表达式
    arr.forEach((e) => {
        console.log(e);
    });

    // push: 添加元素到数组末尾
    arr.push(7, 8, 9);
    console.log(arr);

    // splice: 删除元素
    arr.splice(2, 2);// 从索引2开始删除2个元素
    console.log(arr);

    </script>

String

javaScripe_JSON_13

<script>
// 创建字符串对象
// var str = new String("Hello String");
var str = "    Hello String    ";

console.log(str);

// length,获取字符串长度
console.log(str.length);

// charAt,获取指定索引处的字符
console.log(str.charAt(4));

// indexOf,查找子串的位置
console.log(str.indexOf("lo"));

// trim,去除字符串两端的空格
var s = str.trim();
console.log(s);

// substring(start, end) ---- 开始索引,结束索引 (含头不含尾)
console.log(s.substring(0, 5));
</script>

JSON

自定义对象

javaScripe_html_14

<script>
// 自定义对象
var user = {
    name: "Tom",
    age: 10,
    gender: "male",
    eat(){
        alert("用膳~");
    }
};

alert(user.name);
user.eat();
</script>

javaScripe_字符串_15

javaScripe_JSON_16

<script>
// 定义JSON
var jsonstr = '{"name":"Tom", "age":18, "addr":["北京", "上海", "西安"]}';

// JSON字符串无法直接访问属性,需要先解析成对象
// alert(jsonstr.name); // 这会报错

// JSON字符串 -> JS对象
var obj = JSON.parse(jsonstr);// {"name":"Tom","age":18,"addr":["北京","上海","西安"]}
alert(obj.name);// Tom

// JS对象 -> JSON字符串
alert(JSON.stringify(obj));// {"name":"Tom","age":18,"addr":["北京","上海","西安"]}

</script>

BOM(浏览器对象模型)、DOM(文档对象模型)

javaScripe_字符串_17

window

javaScripe_字符串_18

<script>
// 获取
// window.alert("Hello BOM");
// alert("Hello BOM Window");

// 方法
// confirm - 对话框 - 确认: true,取消: false
var flag = confirm("您确认删除该记录吗?");
alert(flag);

// 定时器 - setInterval - 周期性地执行某一个函数
var i = 0;
setInterval(function() {
    i++;
    console.log("定时器执行了" + i + "次");
}, 2000);

// 定时器 - setTimeout - 延迟指定时间执行一次
setTimeout(function() {
    alert("JS");
}, 3000);
</script>

location

javaScripe_JSON_19

<script>
// location
alert(location.href);

// 跳转到指定网址
location.href = "https://www.baidu.com";

</script>

DOM(文档对象模型)

javaScripe_JSON_20

示例

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>课程表</title>
    <style>
        table {
            width: 60%;
            margin: auto;
            border-collapse: collapse;
            text-align: center;
        }
        th, td {
            border: 1px solid black;
            padding: 8px;
        }
        h2 {
            text-align: center;
        }
    </style>
</head>
<body>
    <h2 id="title">课程表</h2>
    <table>
        <tr>
            <th>学号</th>
            <th>姓名</th>
            <th>分数</th>
            <th>评语</th>
        </tr>
        <tr>
            <td>001</td>
            <td>张三</td>
            <td>90</td>
            <td>很优秀</td>
        </tr>
        <tr>
            <td>002</td>
            <td>李四</td>
            <td>92</td>
            <td>优秀</td>
        </tr>
        <tr>
            <td>003</td>
            <td>王五</td>
            <td>83</td>
            <td>很努力,不错</td>
        </tr>
        <tr>
            <td>004</td>
            <td>赵六</td>
            <td>98</td>
            <td>666</td>
        </tr>
    </table>
    <div style="text-align: center; margin-top: 20px;">
        <button onclick="changeTitleContent()">改变标题内容</button>
        <button onclick="changeTitleColor()">改变标题颜色</button>
        <button onclick="deleteLastRow()">删除最后一个</button>
    </div>

    <script>
        function changeTitleContent() {
            document.getElementById("title").textContent = "新的课程表";
        }

        function changeTitleColor() {
            document.getElementById("title").style.color = "blue";
        }

        function deleteLastRow() {
            var table = document.querySelector("table");
            var rowCount = table.rows.length;
            if (rowCount > 1) {
                table.deleteRow(rowCount - 1);
            }
        }
    </script>
</body>
</html>

javaScripe_JSON_21

javaScripe_字符串_22

拿到元素之后,可以使用一些方法来修改元素内容。

DOM案例

javaScripe_html_23

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>点亮灯泡</title>
    <style>
        .light-off {
            background-color: gray;
        }
        .light-on {
            background-color: yellow;
        }
    </style>
</head>
<body>
    <div id="lightBulb" class="light-off" style="display:inline-block; width:100px; height:150px;"></div>
    <div id="text1">教育</div>
    <div id="text2">程序员</div>

    <div>
        <input type="checkbox" id="checkbox1">电影
        <input type="checkbox" id="checkbox2">旅游
        <input type="checkbox" id="checkbox3">游戏
    </div>

    <button onclick="lightUp()">点亮灯泡</button>

    <script>
        function lightUp() {
            // 点亮灯泡
            const lightBulb = document.getElementById('lightBulb');
            lightBulb.classList.remove('light-off');
            lightBulb.classList.add('light-on');

            // 在所有div标签内容后加上 "very good"
            var divs = document.getElementsByTagName('div');
            for (let i = 0; i < divs.length; i++) {
                const div = divs[i];
                div.innerHTML += "<span style='color:red'> very good</span>";
            }


            // 选中所有复选框
            document.querySelectorAll('input[type="checkbox"]').forEach(checkbox => {
                checkbox.checked = true;
            });
        }
    </script>
</body>
</html>

5.js事件监听

javaScripe_html_24

事件绑定

javaScripe_字符串_25

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JS事件绑定示例</title>
</head>
<body>
    <input type="button" id="btn1" value="事件绑定1">
    <input type="button" id="btn2" value="事件绑定2">

    <script>
        function on() {
            alert("按钮1被点击了...");
        }

        // 等待页面加载完成后绑定事件
        window.onload = function() {
            document.getElementById('btn1').onclick = on;

            document.getElementById('btn2').onclick = function() {
                alert("按钮2被点击了...");
            };
        };
    </script>
</body>
</html>

常见事件

javaScripe_字符串_26

案例

javaScripe_JSON_27

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>灯泡控制</title>
    <style>
        .light {
            width: 100px;
            height: 150px;
            margin: 10px;
            display: inline-block;
            background-color: gray;
        }
        .on {
            background-color: yellow;
        }
        input[type="text"] {
            display: block;
            margin-top: 10px;
            font-size: 16px;
        }
    </style>
</head>
<body>
    <div id="lightBulb" class="light"></div>
    <button onclick="turnOn()">点亮</button>
    <button onclick="turnOff()">熄灭</button>
    <input type="text" id="inputField" placeholder="IT" onfocus="toLowerCase()" onblur="toUpperCase()">

    <div>
        <input type="checkbox" id="checkbox1">电影
        <input type="checkbox" id="checkbox2">旅游
        <input type="checkbox" id="checkbox3">游戏
        <button onclick="selectAll()">全选</button>
        <button onclick="invertSelection()">反选</button>
    </div>

    <script>
        function turnOn() {
            document.getElementById('lightBulb').classList.add('on');// 添加on类
        }

        function turnOff() {
            document.getElementById('lightBulb').classList.remove('on');// 移除on类
        }

        function toLowerCase() {
            const input = document.getElementById('inputField');
            input.value = input.value.toLowerCase();// 将输入框中的内容全部转换为小写
        }

        function toUpperCase() {
            const input = document.getElementById('inputField');
            input.value = input.value.toUpperCase();// 将输入框中的内容全部转换为大写
        }

        function selectAll() {
            document.querySelectorAll('input[type="checkbox"]').forEach(checkbox => {
                checkbox.checked = true;
            });
        }

        function invertSelection() {
            document.querySelectorAll('input[type="checkbox"]').forEach(checkbox => {
                checkbox.checked = !checkbox.checked;
            });
        }
    </script>
</body>
</html>