JavaScript Quick Start

1. Concept

JavaScript is a client-side scripting language (without compilation, execution can be resolved directly browser), running in the client browser, the browser has JavaScript parsing engine.

JavaScript effects

  • Increase user interaction with the html page, so that html page has a number of dynamic effects, enhance the user experience.

JavaScript development history

  1. In 1992, Nombase company, developed the first door client-side scripting language designed for form validation, named: C--. After JScript appear, renamed ScriptEase.

  2. In 1995, Netscape (Netscape) company, has developed a client-side scripting languages: LiveScript. SUN company later hired experts, modify LiveScript, eventually named JavaScript.

  3. In 1996, Microsoft developed a plagiarism JavaScript JScript language.

  4. In 1997, ECMA (European Computer Manufacturers Association) to develop a standard for all client-side scripting languages: ECMAScript.

So, JavaScript = ECMAScript + JavaScript something unique (BOM + DOM)

2. ESMAScript: standard client-side scripting language

2.1 The basic syntax

2.1.1 combined with the way html

We use the <script>tag to JavaScript and html files to combine internal and external JS JS two ways.

In use <script>prior to labels, we should know the following two considerations:

  1. Html page in any position , you can use <script>the tag, but the order is executed html code, that is, the JavaScript code is written in a different location would affect the situation page .

  2. In a html file, ** you can define multiple <script>tags.

1. Internal JS

Used <script>labels, JavaScript code is written in the tag body.

Sample code:

<script>
    alert("内部JS");
</script>

2. External JS

Defined <script>tags, by the introduction of external js file src attribute.

Sample code:

<script src='js/a.js'></script>

2.1.2 Notes

Notes Java language and manner consistent with single-line and multi-line comments two kinds.

  1. Single-line comments : // footnotes

  2. Multi-line comments : / * comment * content /

2.1.3 Data Types

In the types of data types and Java language consistent with the original data into data types and reference types; but the type of data and Java vary.

1. Original data type

  1. number

    digital. It is divided into an integer, decimal, and NaN (not a number, not a number of numeric type) three. NaN any digital phase computation result or NaN.

  2. string

    For string, we have two things to note:

    1. The String is a Java class, and therefore is a reference data type; but in JavaScript, string is a primitive data type.

    2. Character does not exist in JavaScript variables, and single and double quotation marks are of type string variable, for example 'a' is a variable of type string.

    However, if the same quotes in quotation marks, is required \to be escaped. Single quotation marks 'escapes ['], double quotes "escapes ["]. Of course, we may also need to quote in double quotes, use single quotes in the inner layer.

  3. boolean

    Boolean variables. Only two kinds of true and false values.

  4. null

    It represents a placeholder object is empty.

  5. underfined

    Representation is not defined. If a variable is declared not initialized value, it will be implicitly assigned a underfined.

2. The reference data types

That is, objects, and other object-oriented languages ​​meaning that is consistent.

2.1.4 Variables

Variable : a memory for storing data

JavaScript and Java different, Java is a strongly typed language , while JavaScript is a loosely typed language .

  • Strongly typed language : when to open up the memory space, defines the data type of data storage space. You can only store a fixed type of data .

  • Weakly typed language : When you open up the memory space, do not define the data types of data storage space. You can store different types of data .

Using variable syntax

  • Define the variable:var 变量名 = 变量值

  • See variable types: Use typeof(变量名)the function can check the type of a variable, for example (num) typeof

JavaScript, we can use the output string html code in the form of , for example, document.write("<input type='text' />")will print a text input box on the page.

JavaScript variable type of conversion

In JavaScript, if the variable is not the type of calculation involved in operations comply with the requirements, then the JavaScript engine will automatically variable type conversion.

  • Other types of transfer type number

    1. string turn number

      Converted in accordance with the literal value; if the string literal is not a number, it will turn NaN.

    2. boolean 转 number

      true converted to 1, false into 0.

  • Other types of transfer type boolean

    1. number 转 boolean

      0 or NaN is false, the other number is true.

    2. string 转 boolean

      In addition to the empty string ( ""), the other is true.

    3. boolean or null turn underfined

      null and underfined are false.

    4. Reference data types

      All references to data types, as long as the presence of (i.e. not null), are true.

When you call typeof null is actually returns the "object". This is actually a bug JavaScript in, but was followed ECMAScript, but technically, null is still one of the original value.

2.1.5 Operators

Many operators and other programming languages ​​are similar, need to pay attention and language used in their usual usage of different operators

1. Unary operators

Only a number of arithmetic operators: +, -, + (plus), - (minus)

  • Sign (+, -): prior to be used in other types of variables, to force it into a variable number type.

2. Arithmetic Operators

Arithmetic operators generally carried out (+ may be spliced ​​string type variables) based on the type of a variable number, for other types of variable revolution number can be seen the foregoing type conversion.

+, -, *, /,%, etc.

3. assignment operator

=, + =, - =, etc.

4. Comparison Operators

For comparison operators, at the same variable type, direct comparison; if different types of variables, the first type conversion, and then compared.

If the string comparison , press lexicographical compared bitwise to know the outcome of each comparison.

<=,> =,>, <, === (congruent)

  • Full equal to ===: prior to determining the type comparison, if a different type directly returns false.

The logical operators

Logical operator is a boolean variable as a basis for the operation, other types of variables, should be converted into a boolean variable text has introduced before the specific conversion rule.

&&、||、!

6. The ternary operator

表达式 ? 值1 : 值2: Although there appear in Java, but still special note, first determine whether the value of the expression is true, the value of a return to true; false returns the value 2. It is a shorthand judgment statement.

2.1.6 flow control statements

Flow control statements similar to Java, but pay attention to the data type of a switch statement is accepted.

  1. if ... else .. statement

  2. switch statement

    • In Java, switch statement accepts byte, int, short, char, enumeration (1.5 start) and String (1.7 start) of the six data types only.

    • In JavaScript, switch statements, receive any primitive data types .

  3. while statement

  4. Statement do ... while ...

  5. for statement

2.1.7 special syntax

Here to talk about the differences JavaScript and Java syntax.

  1. JavaScript, the statement need not be a semicolon ;at the end, if only one line statement can not add a semicolon; but in order to standardize considered best not to omit the semicolon.

  2. JavaScript when you declare a variable, you can not use the var keyword , but simply stating that there will be differences in the time variable method function.

    • Use var to declare variables: declare local variables.

    • Do not use var to declare variables (not recommended): declare global variables.

    But it recommended to always use var to declare variables, as long as all of the in vitro method declaration, even using the var keyword, scope is all js code.

Use JavaScript multiplication table to print the following figure:

Multiplication table demo

 <html>
    <head>
        <title>九九乘法表</title>

        <style>
            td {
                border: 1px solid;
            }
        </style>

        <script>
            document.write("<table align='center'>");

            for (var i = 1; i <= 9; ++i) {
                document.write("<tr>");
                for (var j = 1; j <= i; ++j) {
                    document.write("<td>");

                    // 输出 1*1=1
                    document.write(i + "*" + j + "=" + (i * j) + "&nbsp;&nbsp;&nbsp;");

                    document.write("</td>");
                }
                document.write("</tr>");
            }

            document.write("</table>");
        </script>
    </head>

    <body>

    </body>
</html>

2.2 Basic Object

2.2.1 Function: function objects

1. Create

  1. Recommended Usefunction 方法名称(element0, element1,...) { 方法体 }

    // 由于所有函数声明都是使用 var 关键字
    // 因此这里可以省略 var 关键字,当然也可以使用 var
    function fun1(a, b) {
        // 方法体
    }
  2. var 方法名 = function(element0, element1,...) { 方法体 }

    var fun2 = function() {
        // 方法体
    }
  3. (Not common, you can understand)var fun = new Function(形式参数列表, 方法体);

2. Common property

  • length: parameter representative of the number of

3. Features

  1. Parameters passed to the method can not use the var keyword to declare type (var keyword because only this kind of declaration of variables), also did not return type .

  2. The method is an object , defining the name of the same method, a new method overrides the old method (ie, overloading does not exist).

  3. In JavaScript, call the method with only the name of the method is related to and unrelated to the argument list.

  4. In the method declaration, there is a hidden built-in objects (array) arguments, encapsulates all of the actual parameters, which makes the JavaScript method uses unusual flexibility.

See code like

function addAll() {
    var sum = 0;
    // 算出所有传入参数的和
    for (var i = 0; i < arguments.length; i++) {
        sum += arguments[i];
    }
    return sum;
}

var sum = addAll(1, 2, 3);
alert(sum);

Run results shown in Figure:

function demo

2.2.2 Array: an array of objects

1. Create

  1. var 数组名 = new Array(element0, element1,...)

  2. var 数组名 = new Array(size)

  3. var 数组名 = [element0, element1,...]

  4. var 数组名 = new Array()

var arr1 = new Array(1, 2, 3);
var arr2 = new Array(5);
var arr3 = [1, 2, 3, 4];
var arr4 = new Array();     // 创建一个空的数组

// 需要注意的是,如果我们希望创建初始只含一个元素的数组
var arrOneEle = [4];    // 这是对的,只含一个元素4
// var arrError = new Array(4);  错误的写法,这样是创建长度为4的数组

2. Features

  1. An array can have multiple types of elements .

  2. Variable-length arrays (array length will grow automatically, Java-like collections).

See follows a set of codes:

var arr = [1, "string", true];

// 依次输出1,string 和 true
document.write(arr[0] + "<br/>");
document.write(arr[1] + "<br/>");
document.write(arr[2] + "<br/>");

// 虽然数组初始长度是3,我们也可以直接使用arr[5]
arr[5] = "auto";
// 能够正确地输出 atuo
document.write(arr[5] + "<br/>");

// 因为arr[4]没有定义,所以会输出 underfined
document.write(arr[4] + "<br/>");

Run shot as follows:

Example of use arr

3. The common method

  1. join(分隔符): The elements of the array in a given splice delimiter and returns a string (if not specified delimiter, the default comma ',' as a separator)

  2. push(元素): Adding an element in the array tail

2.2.3 Date: Date Object

Date of similar objects in Java

1. Create

  1. var date = new Date();

2. The common method

  1. toLocalString(): Return the current date to the local computer time string format.

  2. getTime(): Date object returns the current time and milliseconds at 0:00 on January 1, 1970 the difference.

To be learned

Math

Regexp

Global

Boolean

Number

String

3. GOOD

The BOM (BrowserObjectModel), the browser object model, the browser is encapsulated component.

What makes up a browser

  1. Nevigator Object : the browser itself (not important)

  2. The window object : html tab page corresponding overall

    In the window object, like a browser, the following objects:

    1. Location object : Object address bar

    2. History Object : Object history

    3. Screen object : a display object, the entire computer screen (not important)

It may be noted that the above objects window object does not contain the body of the page. In fact, because this part of the body of the page is too important, it alone into the DOM of this class in the document objects .

BOM Object diagram:

GOOD

3.1 window objects

window without creating an object , you can directly call the keyword [window]

使用window中的方法时,window引用可以省略,也就是可以直接通过方法名进行调用,例如alert()方法就是window中的方法,这是,实际上是当前标签页的window对象调用了这些方法,类似与 Java 中的 this。

1.常用方法

  1. 与弹出提示窗有关的方法

    1. alert():显示带有一段消息和一个确认按钮的警告框。

    2. confirm():显示带有一段信息以及确认按钮和取消按钮的对话框。

    confirm方法的返回值为boolean类型。如果用户点击确认则返回true,用户点击取消则返回false。

    confirm的示例代码:

    var hasConfirm = confirm(这是confirm,确认对话框);
    
    // 根据用户点击不同按钮会有不同的弹窗
    if (hasConfirm) {
        alert("点击了确认");
    } else {
        alert("点击了取消");
    }
    1. prompt(string):显示可提示用户输入的对话框。

    可以向prompt方法传入string类型的参数(其实在js中其他类型的变量也会被转换成string),这个传入的string就是出现输入框时会出现的提示字符。

    prompt方法的返回值是一个string类型的变量,是用户在输入框中输入的值。

    prompt示例代码:

    var inputString = prompt("可以在该对话框进行输入");
    
    // 这里会弹出用户刚刚输入的值
    alert(inputString);
  2. 与窗口的打开和关闭有关的方法

    1. open("url"):在新窗口中打开指定url,如果没有指定url则会打开一个空白页。返回值是打开的新窗口的window对象。

    2. window.close()关闭调用这个close方法的window对象,如果直接使用close方法,其实是用当前页面的window对象调用了close方法,也就是关闭当前页面。

  3. 与定时器有关的方法

    1. setTimeout("js代码", number)一次性定时器,在指定number(会自动转换为整数)的毫秒后调用一次传入的js代码,之后不再起作用。

    setTimeout方法的返回值是这个定时器的id,id是一个number类型的变量。

    setTimeout方法示例:

    function fun() {
        alert("时间到了");
    }
    
    // 下面三个语句是等价的
    setTimeout(fun, 2000);
    setTimeout("fun();", 2000);
    setTimeout("alert('时间到了');", 2000); // 注意,在这里我们在双引号中需要使用引号时使用了单引号,否则要对内部的双引号进行转义
    1. setInterval("js代码", number)循环定时器,每隔指定number(会自动转换为整数)的毫秒就调用传入的js代码。用法和setTimeout方法类似。

    2. clearTimeout(id)撤销指定id的定时器(其实定时器id就是一个number类型的变量),其调用后撤销对应id的定时器。

2.常用属性

  1. 获取其它BOM对象的属性

    1. history:获取history对象

    2. location

    3. Navigator

    4. Screen

  2. 获取DOM对象

    1. document:所以,我们使用使用DOM的document.方法时,实际上是先用当前标签页的window获取了DOM对象,再通过DOM对象调用方法。

3.2 Location对象

我们可以通过window.locationlocation来获取一个location对象。

1.常用方法

  1. reload():重载当前文档,即刷新当前页面。

    在页面上实现一个刷新按钮:

    <body>
    // 这里直接将按钮和js代码耦合了
    <input type='button' id='button' value='刷新' onclick='reload();' />
    <body>

2.常用属性

  1. href:浏览器地址,要改变Location的地址(即要将当前标签页前往另一个网址),地址前面要加【http】或【https】协议。

3.3 History对象

History 对象包含用户在当前标签页中访问过的 URL。

和Location对象类似,我们可以通过window.historyhistory来获取一个history对象。

1.常用方法

  1. back():加载 history 列表中的上一个 URL。

  2. forward():加载 history 列表中的下一个 URL。

  3. go(number):加载 history 列表中的某个具体页面,具体情况根据 number 的值决定。

    对于go方法中,我们希望传入的 number 参数是一个整数,如果是一个正数,则是前进正数个历史纪录;如果是一个负数,则后退其绝对值个历史纪录。例如,-5为后退5个历史纪录。

    也就是说,history.go(-1)history.back()是等价的;同样的,history.go(1)history.forward()是等价的。

2.常用方法

  1. length:返回当前标签页的历史 URL数目。

4. DOM

当网页被加载时,浏览器会创建页面的文档对象模型 DOM(Document Object Model)。

DOM(Document Object Model),文档对象模型,将标记语言文档(即html文档)封装成一个对象。

DOM 是 W3C(万维网联盟)的标准,定义了访问 HTML 和 XML 文档的标准。

W3C DOM 标准被分为三个不同的部分:

  1. 核心 DOM:针对任何结构化文档的标准模型

    • Document:文档对象

    • Element:元素对象(也就是 HTML 中的标签)

    • Text:文本对象(HTML 表单中的文本输入域,如 text 类型的 input)

    • Comment:注释对象(就是 HTML 中的注释)

    • Attribute:属性对象(每个标签对应的每个属性都是一个属性对象)

    • Node:节点对象,上述5个对象的父对象

  2. HTML DOM:针对 HTML 文档的标准模型

  3. XML DOM:针对 XML 文档的标准模型

HTML 的 DOM 模型将被构造为对象的树:

dom tree

上述的树形图并不用强行记忆,如果我们拥有一个良好的 html 编码规范的话,我们可以发现上面树形结构和 html 中的缩进格式是相对应的。

通过使用 DOM,JavaScript 拥有以下能力,可以用于创建一个动态的 HTML:

  • 改变页面中所有的 HTML 元素

  • 改变页面中所有的 HTML 属性

  • 改变页面中所有的 CSS 样式

  • 对页面中所有事件做出反应

4.1 核心 DOM

HTML DOM 对原生的核心 DOM 修改比较多而 XML DOM 对其修改比较少。因此我们在学习核心 DOM 时可以查找 XML DOM 的资料。

1.Document 对象

Document 对象的位置在前文 BOM 对象的布局管理中出现过,其实就是标签页中 html 起作用的那块主体部分。

对于 HTML,我们可以使用 window 对象来获取 document 对象,window.documentdocument是等价的。

1. 常用方法

  1. 获取 Element 对象

    1. getElementById(id):根据元素 id 来获取特定元素,id 属性值一般唯一。

    2. getElementByNmae("name"):根据元素名称来获取符合名称的元素对象。

      因为元素的 name 可能重复,所以 getElementByName 方法返回值是一个元素数组。

    3. getElementByClassName("class"):根据元素的 class 来获取该类型的元素对象。

      和 getElementByName 方法类似;因为元素的 class 可能重复,所以 getElementByClassName 方法返回值是一个元素数组。

    4. getElementByTagName("element"):根据元素的种类来获取该类型的元素对象。例如getElementByTagName("div")就是获取所有 div 标签元素的集合。

      显然,一个页面中可以出现很多个同一种类的元素,所以 getElementByTagName 方法的返回值也是一个元素数组。

2.创建其它 DOM 对象

在学习以下方法之前,我们要知道核心 DOM 总共有哪些对象;共6个对象,Element、Comment、Text、Document和Node,这在本章节开头有介绍。

  1. createAttribute(name):创建指定名称的属性节点,并返回新的元素对象 Attribute。

  2. createComment():创建注释节点

  3. createElement():创建一个新的元素对象

  4. createTextNode(value):创建文本节点

4.1.1 Element 对象

获取/创建

通过前文介绍的方法,使用 document 来获取和创建。

常用方法

  1. setAttribute("属性名", "属性值"):设该元素特定属性的属性值

  2. removeAttribute("属性名"):删除该元素的特定属性

    例如:

    <body>
        <a>测试用标签</a>
    </body>
    
    <script>
    // 1. 获取前面的超链接标签
    //  因为只有一个,所以可以直接指定为数组中元素索引0的元素
    var element_a = document.getElementByTagName("a")[0];
    // 2. 设置超链接的目标地址
    element_a.setAttribute("href", "https://www.baidu.com");
    // 3. 移除超链接的目标地址
    element_a.removeAttribute("href");
    </script>

4.1.2 Node 对象

所有的 DOM 对象都可以当作一个 Node 对象使用,它们构成了一个 DOM 树。

1.常用方法

对 DOM 树进行 CRUD 操作

  1. appendChild():在当前节点的子节点列表的结尾添加新的子节点

  2. removeChild(子节点对象):删除(并返回)当前节点的指定子节点,没有给定节点无法执行

  3. replaceChild():用新节点替换一个子节点

<body>
    <!-- 定义一个存在子节点的标签元素 -->
    <div id='parent'>
        父标签
        <div id='child'>子标签</div>
    </div>
    <!-- 将超链接href 像下面一样定义可以让查连接被点击后不进行跳转 -->
    <a href='javascript:void(0)' id='delete'>删除子节点</a>
    <!-- 用于新增子节点的按钮 -->
    <input type='button' id='add' value='新增子节点' />

    <script>
    // 1. 获取超链接
    var e1 = document.getElementById('delete');
    var e2 = document.getElementById('add');

    var div_parent = document.getElementById("parent");
    var div_child = document.getElementById("chile");

    // 2. 绑定删除子节点事件
    e1.onclick = function() {
        // 移除div_parent的子节点div_child
        div_parent.removeChild(div_child);
    }

    // 3. 绑定新增子节点事件
    e2.onclick = function() {
        // 创建一个新的div节点       
        var newDiv = document.createElement("div");
        // 为新节点设置id
        newDiv.setAttribute("id", "second_child");
        // 将新节点设置为parent节点的子节点
        div_parent.appendChild(newDiv);
    }
    </script>
</body>

2.常用属性

  1. parentNode:当前节点的父节点

4.2 HTML DOM

HTML DOM 是关于如何获取、修改、添加和删除 HTML 元素的标准。

1.对页面元素进行操作

  1. 获取页面标签(元素)对象 element

    • document.getElementByID("元素ID")

      注意:因为html中代码是顺序执行的,所以上述代码需要书写在对应id的元素定义之后(否则元素还没有加载,也就无法获取id)。

  2. 操作Element对象

    1. 修改属性值:element.attr(修改class时,使用element.className这个属性)
    <img id='imgID' src='img.old.gif' />
    // 修改id为imgID的图片对象的图片路径
    var img = document.getElementByID("imgID");
    light.src = "img/new.gif";
    1. 修改标签体内容(围堵标签的标签体):element.innerHTML
    <h1 id='h1ID'>这是旧的标题</h1>
    // 修改标签体内容
    var title = doucument.getElementByID("h1ID");
    title.innerHTML = "这是新的标题";
    1. 修改样式(也可以使用<style标签>

      1. 使用元素的style属性来控制:element.style.attr

      2. 使用<style>标签定义好样式,再通过修改元素的className属性来设置其class属性。

5. 事件相关

5.1 事件的概念

事件:某些组件被执行了某些操作后,出发了某些代码的执行

- 事件:某些操作,如单击、双击等。

- 事件源:组件;如按钮、文本框。

- 监听器:代码。

- 注册监听:将事件、事件源和监听器绑定。当事件源上发生指定事件时触发对应的触发器。

5.2 常见的事件

1.点击事件

  1. onclick:单击事件

  2. onblclick:双击事件

2.焦点事件

  1. onblur: loses focus (typically checking for Form)

  2. onfocus: element gets focus

  • Function: the code components executed after the operation

3. Load Events

  1. onload: a page or image has finished loading

    You can use window.onloadevents to indicate the browser is loaded. (Thus, even if the buttons and bound to js code, the code may be first written js)

    We can use all the events window.onload = function() {事件}this way to write

4. mouse events

  1. onmousedown: the mouse button is pressed

    Can when defining method, passing an event object. We can use event.button confirm which button is clicked.

    For event.button, 0,1,2 representing the left, middle and right.

    doucument.getElementById("button").onmousedown = function(event) {
        alert(event.button);
    }
  2. onmouseup: mouse button is released

  3. onmousemove: the mouse is moved

  4. onmouseover: mouse over an element

  5. onmouseout: mouse away from an element

5. Keyboard events

  1. onkeydown: A keyboard key is pressed

    And onmousedown Similarly, by event.keyCodedetermining which keys are pressed.

  2. onkeyup: A keyboard key is released

  3. onkeypress: a keyboard key is pressed and then is released

6. Select and change

  1. onchange: content domain is changed

  2. onselect: text is selected

7. The form events

  1. onsubmit: Confirm button is clicked (can be used to prevent a form of submission)

    Two kinds of ways to prevent form submission:

    <script>
    // 校验表单的函数
    function checkForm() {
        // 写入自己的判断语句
    
        // 返回值应该为 boolean 类型变量,此处暂定返回false
        return false;
    }
    
    // 1. 使用onsubmit属性
    window.onload = function() {
        document.getElementById("form").onsubmit = checkForm;
    }
    
    </script>
    
    <!-- 2. 设置onclick -->
    <!-- 这里只是为了说明:onclick方法后的js语句要特别注意 -->
    <form id='form' onclick='return checkForm();'>
    <!-- 表单语句... -->
    </form>
  2. onreset: Reset button is clicked

Binding events

  1. Designated events directly on the html tag attributes, attribute values ​​is actually js code string:

    /* 设置imgID图片,在被点击时执行相应的js代码:弹出一个窗口提醒 */
    
    /*-------------------------------------------------------------*/
    // 直接在属性值指定js代码
    <img id='imgID' src='img/old.gif' onclick='alert("我被点击了");'>
    
    /*-------------------------------------------------------------*/
    // 属性值指定js函数,间接调用js代码
    // 注意,因为html代码是顺序执行的,所以函数要在调用函数之前定义
    <script>
        function fun() {
            alert("我被点击了");
        }
    </script>
    
    <img id='imgID' src='img/old.gif' onclick='fun()'>

    Although this method is simple, but may be coupled together with the html tag js code, it is not conducive to expansion and subsequent maintenance.

  2. Js element obtained by the object attribute specified event, a function is provided with a corresponding property of the event bound to.

    // 在js代码之前就需要事先定义好图片元素
    <img id='light' src='img/light.gif'>
    
    <script>
    // 获取图片对象(假设是一个灯泡的图片)
    var light = document.getElementByID("light");
    
    // 初始情况下灯泡是关着的
    var flag = false;
    
    // 这样每次点击图片都会有不同的事件
    function fun() {
        if (flag) {
            alert("开灯");
        } else {
            alert("关灯");
        }
        flag = !flag;
    }
    
    // 绑定事件
    light.onClick = fun;
    </script>

Guess you like

Origin www.cnblogs.com/Bylight/p/11279977.html