JS (JavaScript)

1. JavaScript, an interpreted scripting language that runs in the JavaScript interpreter

 1. The main uses of JavaScript : JavaScript mainly reads and writes HTML elements, embeds dynamic text in web pages, and dynamically modifies them. CSS style sheet; respond to browser events, form data validation, detect visitor’s browser information, etc.;

?2. Related applications of JavaScript: Verification data; page special effects; numerical calculations; dynamic page effects

3. JavaScript location: We can place JavaScript code anywhere in the html file, but we usually place it in the head or body part of the web page; place it in part, the most common way is to place the ; 3 , placed in the attribute of the HTML tag starting with on, that is, the event handler;

5. JavaScript output: 1. Use Windows.alert() to pop up a warning box; 2. Use the Document.write() method to write the content into the HTML document (document object, representing the entire HTML document, available to access all elements in the page); 3. Use innerHTML to write to HTML elements; 4. Use console.log() to write to the browser's console;

6. A complete JavaScript implementation should consist of the following three parts:1. Core, ECMAScript; 2. Document Object Model, DOM, document object model; 3. Browser Object Model, BOM, browser object model;

?Through core objects, DOM objects, and BOM objects, it acts on HTML elements

2. JavaScript core

1.Data type, JavaScript data types include the following: Numeric type: numbers with or without a decimal point; String type: text surrounded by quotes; Boolean type: only two values, true false, non-0 or non-null is true; null type: represents a value that has never been assigned, there is only one value null, refers to an undefined variable, returns null; undefined type: Specifically used to determine a variable that has been created but has no initial value;

Numerical type, in JavaScript, all numbers are floating point;

When a number appears directly in a JavaScript program, it is called a numerical literal. The numerical literals supported by JavaScript include integer data, hexadecimal and octal data, and floating-point data. Note that the negative sign is a unary value. Inverse operator, not part of numeric literals;

The toFixed() method can round the number to a number with a specified number of decimal places. The return value is string type, typeof, check the data type.

String type, string string is a sequence composed of Unicode characters, numbers, punctuation marks, etc. It is the data type used by JavaScript to represent text;

String data is contained in single quotes and double quotes; a string delimited by single quotes can contain double quotes, and a string delimited by double quotes can also contain single quotes; it can be double inside or single outside. The format allows the output string to be enclosed in double quotes. If the outer double form is used to allow the string to be enclosed in double quotes, the escape character " can be used; the string can be connected using the + sign;

Boolean type, the Boolean data type has only two values. These two legal values are represented by the direct quantities true and false respectively, which indicate whether something is true or false;

JavaScript converts true to 1 and false to 0 when necessary

The null type, null, means that the value is empty and is used to define empty or non-existent references; if a reference is made to an undefined variable, a null value is returned, and null is not equivalent to an empty string or 0;

Undefined type. A variable of an undefined type is undefined, which means that the variable has not been assigned a value, or a non-existent attribute value has been assigned. In addition, there is a special type of numeric constant NaN in JavaScript, which is "not a number". When the program is due to If the calculation is incorrect for some reason, a meaningless number will be generated. At this time, the value returned by JavaScript is NaN.

?The difference between null and undefined is that null means that a variable has been assigned a null value, while undefined means that the variable has not yet been assigned a value

 Escape character type, special characters that cannot be displayed starting with a backslash are usually called control characters, also known as escape characters; in document.write() When an escape character is used in a statement, it will only work if it is placed within the formatted text tag


Object type, composite data type; the value is a combination of basic data types;

?Composite data type, json traversal

 JavaScript JSON, the full English name of JSON is JavaScript Object Notation, is an independent language, a format used to store and transmit data, and is usually used by the server to transmit data to web pages;

JSON syntax rules: Data is key/value pairs; data is separated by commas; curly brackets save objects; square brackets save arrays;

JSON is formatted into JavaScript objects. The syntax of JSON format is the same as the code to create JavaScript objects, so JavaScript programs can easily convert JSON data into JavaScript objects;

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>
        <script>
            var text = '{ "sites" : [' +
                       '{ "name":"Runoob" , "url":"www.runoob.com" },' +
                       '{ "name":"Google" , "url":"www.google.com" },' +
                       '{ "name":"Taobao" , "url":"www.taobao.com" } ]}';
            
            document.writeln(typeof text + "<br/>");
            
            var obj = JSON.parse(text);
            document.writeln(typeof obj.sites + "<br/>");
            
            /* obj = obj.sites;
            for(var i=0; i<obj.length; + + i){
                document.write(obj[i].name + " " + obj[i].url + "<br/>");
            } */
            for(var i=0; i<obj.sites.length; + + i)
                document.write(obj.sites[i].name + " " + obj.sites[i].url + "<br/>");
        </script>
    </body>
</html>

Automatic conversion of data types, when strings are connected with other types using +, other types will be converted to strings, and other operators -, *, /, % will be converted to Number type; Data type coercion, parseInt(), parseFloat() functions;

typeofoperator, returns the type information as a string. There are 6 return values, number, string, boolean, object, undefined, function

2. Variables The main function of variables is to access data and provide a container for storing information; JavaScript is a weakly typed language, and the definition of variables does not require declaring the variable type; JavaScript variables are dynamic types, the same Variables can be used as different types; variables can be declared explicitly using the keyword var, and implicitly declared variables are global variables; multiple variables can be declared at the same time using var, Variables can be assigned values (can be values of different data types), or they can not be assigned values, and only declare unassigned variables. The default value is undefined;

3. Function The definition of a function is implemented using the function keyword. The format is as follows:

function function name (formal parameter list){
    Function body statement block;
}

Function, like other JavaScript, must be located between tags; can a function have a return value or not? The return value is achieved through the return keyword plus an expression. ; function call: directly called as a function; called as a method of an object; used as a constructor; indirectly called through the call and apply methods;

JavaScript can be executed when an event occurs. Therefore, HTML DOM events can call functions, such as the onmouseover event;

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>
        <p id="bgcolor" onmouseover="myfunction()" style="background-color: red;color:#FFFFFF;">Mouse over to change the background color</p>
        
        <script>
            function myfunction(){
                var element=document.getElementById("bgcolor");
                if(element.style.backgroundColor.match("red")){
                    element.style.backgroundColor = "blue";
                    element.style.color = "#FFFFFF";
                    element.innerHTML = "Mouse over to change the background color";
                }
                else{
                    element.style ="background-color: red;";
                    element.style.color = "#FFFFFF";
                    element.innerHTML = "Mouse over to change the background color";
                }
            }
        </script>
    </body>
</html>

The scope of the variable

 <script>
       var a = "global variable";
       function myfun(){
           document.write(a);
           var a = "internal variable";
           document.write(a);
       }
       myfun();
       document.write(a);
    </script>

Image switching

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Image switching</title>
    </head>
    <style>
        #image{
            display: block;
            width: 500px;
            height: 180px;
            margin: 10px auto;
        }
        #next{
            margin-left: 350px;
        }
    </style>
    <body>
        <img src="./images/1.gif" id="image" />
        <button id="next">next</button>
        <button id="prev">prev</button>
         
        <script>
            var image = document.getElementById('image');
            var next = document.getElementById("next");
            var prev = document.getElementById('prev');
            var nowIndex = 1;
            var count = 6;
             
            next.onclick = function(){
                nowIndex = nowIndex + 1>count?1:nowIndex + 1;
                image.src = "img/" + nowIndex + ".jpg";
            }
            prev.onclick = function(){
                nowIndex = nowIndex<=1?count:nowIndex-1;
                image.src = "img/" + nowIndex + ".jpg";
            }
        </script>
         
    </body>
</html>

4. Control statements, control statements, if, if else, switch, while, for, try catch

 try catch

 <script>
        var txt="";
        function message()
        {
            try {
                adddlert("Welcome guest!"); //Wrong function name
            }
            catch(exception)
            {
                txt="There is an error on this page." + "<br/>";
                txt + ="Error description:" + exception.message + "<br/>";
                document.write(txt);
            }
        }
        message();
    </script>

Guess the number

 <script>
        var num = Math.floor(Math.random() * 100 + 1); //Generate a random integer between 1 and 100
        do {
            var guess = parseInt(prompt("The following is a guessing game\
Please enter an integer between 1-100:", ""));
            if (guess == num) {
                alert("^_^, Congratulations, you guessed it right, the lucky number is: " + num);
                break;
            } else {
                if (guess > num) {
                    alert("^_^, the number you guessed is too high");
                    go_on = confirm("Do you want to continue the game?");
                } else {
                    alert("^_^, the number you guessed is too small");
                    go_on = confirm("Do you want to continue the game?");
                }
            }
        } while (go_on);
        alert("Thank you for participating in the game!");
    </script>

99 multiplication table

<table border="0" cellpadding="6" style="border-collapse:collapse;background-color:#FFFFFF;">
<script>
for (var i = 1; i < 10; i + + ) {
    document.write("<tr>");
    for (j = 1; j < 10; j + + )
        if (j <= i)
            document.write("<td style='border:2px solid #004B8A;color: #; background:#ff5500;'>" +
            i + "*" + j + "=" + (i * j) + "</td>");
    document.write("</tr>");
}
</script>
</table>

?5.JavaScript Object

 JavaScript Object

 Array, Boolean, Date, Math, Number, String, RegExp, Functions (Global, top-level functions and their properties), Events (events are usually used in conjunction with functions, so that they can be events to drive function execution);

Array object, (array, indexed array, associative array, array API function)

The Array object's prototype attribute enables you to add attributes and methods to the object. It's very interesting. The syntax for adding attributes is: object.prototype.name= value;

 <script type="text/javascript">
            function employee(name,job,born)//Constructor
            {
                this.name=name;
                this.job=job;
                this.born=born;
            }
            //Create bill object
            var bill = new employee("Bill Gates","Engineer",1985);
            
            employee.prototype.salary=null; // Added salary attribute
            bill.salary=20000; // Attribute assignment
            
            document.write(bill.salary);
        </script>
employee.prototype.show = function() {console.log("prototype adds show method");}

Date object, the Date object uses 1 to represent the first day of the month, but uses 0 to represent the first month of the year; one of the JavaScript timer methods, the Date object: setTimeout() method (another method of the Window object of: setInterval() method);

RegExp object, regular expression test method, syntax: RegExpObject.test(string)

 <script type="text/javascript">
            var str = "Visit phpStudy";
            var patt1 = new RegExp("phpStudy");
            
            var result = patt1.test(str);
            
            document.write("Result: " + result);
        </script>

3. DOM, HTML interface

 What is DOM, document object model, is a W3C standard, document object model, which allows programs and scripts to dynamically access and update the content, structure and style of a document , perform operations such as adding, deleting, modifying and checking web pages.

HTML DOM defines the standard method for accessing and manipulating HTML documents

HTML DOM Object

Document, Anchor, Area, Base, Body, Button, Canvas, Event, Form, Frame, Frameset, IFrame, Image, Input Button, Input Checkbox,Input File, Input Hidden, Input Password, Input Radio, Input Reset, Input Submit, Input Text, Link, Meta, Object, Option, Select, Style, Table, TableCell, TableRow, Textarea;

4. BOM, an API dedicated to operating browser windows;

Browser object

 Window, Navigator, Screen, History, Location;

Window's prompt() method returns value type string; parent is a property of the window object and returns the parent window;

5. The role of the browser kernel : 1. Content layout engine analysis, html and css; 2. Script interpretation engine analysis, js;

6. Find element objects, method:
1. According to the id attribute, accurately search for an element object

var elem = document.getElementById("id");
//Can only be used on documents to find an element, not all elements have ids

2. Search by tag

var elements = parent.getElementsByTagName("tag");
//Find all child nodes with tags under the specified parent node

Can be used on any parent element to check all descendant nodes and return them to the dynamic collection. If only one element is found, use [0] to take it out.

3. Search by name attribute

var elem = document.getElementsByName('name attribute value');
//You can return a collection of all child elements with the specified name attribute value in the DOM tree

4. Search by class

var elements = parent.getElementsByClassName("class");
//There are compatibility issues with ie9
var div = document.getElementById('news');
var list = div.getElementsByClassName('mainTitle');

5. Search through CSS selector

var elem = parent.querySelector("selector");
//Only find one element. Selector supports all selectors in CSS. If the selector matches multiple selectors, only the first one will be returned
var elems = parent.querySelectorAll("selector");
//Find multiple, the selector API returns a non-dynamic collection