JavaScript of Javaweb part I (overall part I)

Generally speaking, javaweb has learned one article. At that time, I just took it over. I didn't practice some things myself and forgot many of them. So I'll review it quickly here. I won't review the contents of HTML and CSS here. I'll review it from JavaScript.

1. JavaScript introduction

  • The birth of JavaScript language is mainly to complete the data verification of the page. Therefore, it runs on the client side and needs to run the browser to parse and execute JavaScript code.
  • JS is a product of Netscape Netscape, which was first named LiveScript; To attract more java programmers. Renamed JavaScript.
  • JS is a weak type and Java is a strong type.
  • characteristic:
    • Interactivity (what it can do is the dynamic interaction of information)
    • Security (direct access to local hard disk is not allowed)
    • Cross platform (any browser that can interpret JS can execute, regardless of the platform)

What is a strongly typed language? For example, when our Java defines a variable, you must specify what type it is, such as int a = 2; js is a weakly typed language, that is, when you specify a variable, you use the form of var a. later, you can define a as int, double, string, etc.

2. Use JS language

(1) The first way

Just use the script tag in the head tag or the body tag to write JavaScript code.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript">
// alert is a warning box function provided by JavaScript language.
// It can receive any type of parameter, which is the prompt information of the warning box
alert("hello javaScript!");
</script>
</head>
<body>
</body>
</html>

(2) The second way

  • First, separate the js code you want to write into a file
  • Then introduce the file you wrote into the file we need to use this code

3. Variables in JavaScript

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript">
var i;
// alert(i); // undefined
i = 12;
// typeof() is a function provided by JavaScript language.
// alert( typeof(i) ); // number
i = "abc";
// It can take the data type of the variable and return
// alert( typeof(i) ); // String
var a = 12;
var b = "abc";
alert( a * b ); // NaN is non numeric, non numeric.
</script>
</head>
<body>
</body>
</html>

4. Syntax content in JS

(1) Relational operation

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript">
var a = "12";
var b = 12;
alert( a == b ); // true
alert( a === b ); // false
</script>
</head>
<body>
</body>
</html>

(2) Logical operation





(3) Array definition


It is a little different from java. When the length of your array is declared as 0, you can also assign values, and then you can also take values.

(4) Function / method

  • Definition format I
<!DOCTYPE html>
<html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript">
    // Define a parameterless function
    function fun(){
        alert("Nonparametric function fun()Called");
    }
// Function call = = = will be executed
// fun();
function fun2(a ,b) {
    alert("Parametric function fun2()Called a=>" + a + ",b=>"+b);
}
// fun2(12,"abc");
// Define a function with a return value
function sum(num1,num2) {
    var result = num1 + num2;
    return result;
}
alert( sum(100,50) );
</script>
</head>
<body>
</body>
</html>
  • Definition format II
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript">
        var fun = function () {
            alert("Nonparametric function");
        }
        // fun();
        var fun2 = function (a,b) {
            alert("Parametric function a=" + a + ",b=" + b);
        }
        // fun2(1,2);
        var fun3 = function (num1,num2) {
            return num1 + num2;
        }
        alert( fun3(100,200) );
    </script>
</head>
<body>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript">
        function fun() {
            alert("Nonparametric function fun()");
        }
        function fun(a,b) {
            alert("Parametric function fun(a,b)");
        }
        fun();
    </script>
</head>
<body>
</body>
</html>
  • arguments parameter in function function
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript">
        function fun(a) {
            alert( arguments.length );//Number of visible parameters
            alert( arguments[0] );
            alert( arguments[1] );
            alert( arguments[2] );
            alert("a = " + a);
            for (var i = 0; i < arguments.length; i++){
                alert( arguments[i] );
            }
            alert("Nonparametric function fun()");
        }
        fun(1,"ad",true);
        // Requirements: it is required to write a function. Used to calculate the sum of all parameters and return
        function sum(num1,num2) {
            var result = 0;
            for (var i = 0; i < arguments.length; i++) {
                if (typeof(arguments[i]) == "number") {
                    result += arguments[i];
                }
            }
            return result;
        }
        alert( sum(1,2,3,4,"abc",5,6,7,8,9) );
    </script>
</head>
<body>
</body>
</html>

(5) js defines the object

  • The first definition form
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript">
        // Definition of object:
        // var variable name = new Object()// Object instance (empty object)
        // Variable name Attribute name = value// Define an attribute
        // Variable name Function name = function() {} / / define a function
        var obj = new Object();
        obj.name = "Huazi";
        obj.age = 18;
        obj.fun = function () {
            alert("full name:" + this.name + " , Age:" + this.age);
        }
        // Object access:
        // Variable name Property / function name ();
        // alert( obj.age );
        obj.fun();
    </script>
</head>
<body>
</body>
</html>
  • The second way
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript">
        // Definition of object:
        // var variable name = {/ / empty object
        // Attribute name: value, / / define an attribute
        // Attribute name: value, / / define an attribute
        // Function name: function() {} / / define a function
        // };
        var obj = {
            name:"Guoge",
            age:18,
            fun : function () {
                alert("full name:" + this.name + " , Age:" + this.age);
            }
        };
        // Object access:
        // Variable name Property / function name ();
        alert(obj.name);
        obj.fun();
    </script>
</head>
<body>
</body>
</html>

5. Events in JS


You can understand what an event is. For example, if you click, it will show a specific effect

  • onload load completion event
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript">
        // Method of onload event
        function onloadFun() {
            alert('Static registration onload Event, all codes');
        }
        // onload event dynamic registration. It's a fixed way of writing
        window.onload = function () {
            alert("Dynamically registered onload event");
        }
    </script>
</head>
<!--Static registration onload event
onload Event is an event that will be triggered automatically after the browser parses the page
<body onload="onloadFun();">
-->
<body>
</body>
</html>
  • onclick click event
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript">
        function onclickFun() {
            alert("Static registration onclick event");
        }
        // Dynamically register onclick events
        window.onload = function () {
// 1 get label object
            /*
            * document Is an object (document) provided by JavaScript language < br / >
            * get obtain
            * Element Element (i.e. label)
            * By Pass.. By.. By...
            * Id id attribute
            *
            * getElementById Get the label object through the id attribute
            **/
            var btnObj = document.getElementById("btn01");
// alert( btnObj );
// 2 through the label object Event name = function() {}
            btnObj.onclick = function () {
                alert("Dynamically registered onclick event");
            }
        }
    </script>
</head>
<body>
<!--Static registration onClick event-->
<button onclick="onclickFun();">Button 1</button>
<button id="btn01">Button 2</button>
</body>
</html>
  • onblur loss of focus event
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript">
        // Event of losing focus in static registration
        function onblurFun() {
// Console is a console object, which is provided by JavaScript language. It is specially used to print out to the browser controller for testing
// log() is the method of printing
            console.log("Event of losing focus in static registration");
        }
        // Dynamically register onblur events
        window.onload = function () {
//1 get label object
            var passwordObj = document.getElementById("password");
// alert(passwordObj);
//2 through the label object Event name = function() {};
            passwordObj.onblur = function () {
                console.log("Dynamic registration loss of focus event");
            }
        }
    </script>
</head>
<body>
user name:<input type="text" onblur="onblurFun();"><br/>
password:<input id="password" type="text" ><br/>
</body>
</html>
  • onchange content change event
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript">
        function onchangeFun() {
            alert("The goddess has changed");
        }
        window.onload = function () {
//1 get label object
            var selObj = document.getElementById("sel01");
// alert( selObj );
//2 through the label object Event name = function() {}
            selObj.onchange = function () {
                alert("The male God has changed");
            }
        }
    </script>
</head>
<body>
Please choose the goddess in your heart:
<!--Static registration onchange event-->
<select onchange="onchangeFun();">
    <option>--goddess--</option>
    <option>Fangfang</option>
    <option>Jiajia</option>
    <option>a queen</option>
</select>
Please choose the male god in your heart:
<select id="sel01">
    <option>--Male god--</option>
    <option>Guoge</option>
    <option>Huazi</option>
    <option>Fucheng</option>
</select>
</body>
</html>
  • onsubmi form submission event
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript" >
        // Static registration form commit transaction
        function onsubmitFun(){
// To verify whether all form items are legal, if one of them is illegal, block the form submission
            alert("Static registration form submission event----Illegal found");
            return flase;
        }
        window.onload = function () {
//1 get label object
            var formObj = document.getElementById("form01");
//2 through the label object Event name = function() {}
            formObj.onsubmit = function () {
// To verify whether all form items are legal, if one of them is illegal, block the form submission
                alert("Dynamic registration form submission event----Illegal found");
                return false;
            }
        }
    </script>
</head>
<body>
<!--return false Form submission can be blocked -->
<form action="http://localhost:8080" method="get" onsubmit="return onsubmitFun();">
    <input type="submit" value="Static registration"/>
</form>
<form action="http://localhost:8080" id="form01">
    <input type="submit" value="Dynamic registration"/>
</form>
</body>
</html>

6. DOM model (key)

(1) Document object



The above points are easy to understand. Now we have a good concept of object-oriented.

(2) Methods in Document objects

  • document.getElementById(elementId)
    Find the dom object of the tag through the id attribute of the tag, and elementId is the id attribute value of the tag
  • document.getElementsByName(elementName)
    Find the dom object of the tag through the name attribute of the tag, and the value of the name attribute of the elementName tag
  • document.getElementsByTagName(tagname)
    Find the dom object by tag name. tagname is the tag name
  • document.createElement( tagName)
    Method to create a label object with a given label name. tagName is the tag name to create
    • For the three query methods of document object, if there is id attribute, the getElementById method is preferred for query
    • If there is no id attribute, the getElementsByName method is preferred for query
    • If there is no attribute getelementsind, check the attribute by name again
      The above three methods must be executed after the page is loaded before the tag object can be queried

(2.1) getElementById method

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript" >
        /*
        * Requirement: when the user clicks the comparison button, the content in the output box shall be obtained. Then verify whether it is legal< br/>
        * The verification rule is: it must be composed of letters and numbers. Underline composition. And the length is 5 to 12 bits.
        * */
        function onclickFun() {
// When we want to operate a tag, we must first obtain the tag object.
            var usernameObj = document.getElementById("username");
// [object HTMLInputElement] it is a dom object
            var usernameText = usernameObj.value;
// How to verify that a string conforms to a certain rule requires the use of regular expression technology
            var patt = /^\w{5,12}$/;
            /*
            * test()Method is used to test whether a string matches my rule,
            * If there is a match, it returns true. false is returned if there is no match
            * */
            var usernameSpanObj = document.getElementById("usernameSpan");
// innerHTML represents the contents of the start tag and the end tag
// innerHTML is readable and writable
            usernameSpanObj.innerHTML = "Brother Guo is so cute!";
            if (patt.test(usernameText)) {
// alert("user name is legal!");
// usernameSpanObj.innerHTML = "user name is legal!";
                usernameSpanObj.innerHTML = "<img src=\"right.png\" width=\"18\" height=\"18\">";
            } else {
// alert("illegal user name!");
// usernameSpanObj.innerHTML = "illegal user name!";
                usernameSpanObj.innerHTML = "<img src=\"wrong.png\" width=\"18\" height=\"18\">";
            }
        }
    </script>
</head>
<body>
user name:<input type="text" id="username" value="wzg"/>
<span id="usernameSpan" style="color:red;">
</span>
<button onclick="onclickFun()">Comparative test</button>
</body>
</html>

(2.2) getElementByName method

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript">
        // Select all
        function checkAll() {
// Make all check boxes selected
// document.getElementsByName(); Is to query and return multiple label object collections according to the specified name attribute
// The operation of this collection is the same as that of an array
// Each element in the collection is a dom object
// The order of their elements in this collection is from top to bottom
            var hobbies = document.getElementsByName("hobby");
// Checked indicates the selected status of the check box. If true is checked, false is unchecked
// The checked attribute is readable and writable
            for (var i = 0; i < hobbies.length; i++){
                hobbies[i].checked = true;
            }
        }
        //Not at all
        function checkNo() {
            var hobbies = document.getElementsByName("hobby");
// Checked indicates the selected status of the check box. If true is checked, false is unchecked
// The checked attribute is readable and writable
            for (var i = 0; i < hobbies.length; i++){
                hobbies[i].checked = false;
            }
        }
        // Reverse selection
        function checkReverse() {
            var hobbies = document.getElementsByName("hobby");
            for (var i = 0; i < hobbies.length; i++) {
                hobbies[i].checked = !hobbies[i].checked;
// if (hobbies[i].checked) {
// hobbies[i].checked = false;
// }else {
// hobbies[i].checked = true;
// }
            }
        }
    </script>
</head>
<body>
hobby:
<input type="checkbox" name="hobby" value="cpp" checked="checked">C++
<input type="checkbox" name="hobby" value="java">Java
<input type="checkbox" name="hobby" value="js">JavaScript
<br/>
<button onclick="checkAll()">Select all</button>
<button onclick="checkNo()">Not at all</button>
<button onclick="checkReverse()">Reverse selection</button>
</body>
</html>

(2.3) getElementByTagname method

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript">
        // Select all
        function checkAll() {
// document.getElementsByTagName("input");
// Is to query according to the specified tag name and return the collection
// The operation of this collection is the same as that of an array
// The collection is full of dom objects
// The order of elements in a collection is their order from top to bottom in the html page.
            var inputs = document.getElementsByTagName("input");
            for (var i = 0; i < inputs.length; i++){
                inputs[i].checked = true;
            }
        }
    </script>
</head>
<body>
hobby:
<input type="checkbox" value="cpp" checked="checked">C++
<input type="checkbox" value="java">Java
<input type="checkbox" value="js">JavaScript
<br/>
<button onclick="checkAll()">Select all</button>
</body>
</html>

(2.4) createElement method

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript">
        window.onload = function () {
// Now we need to use js code to create html tags and display them on the page
// The content of the label is: < div > Brother Guo, I love you < / div >
            var divObj = document.createElement("div"); // In memory < div > < / div >
            var textNodeObj = document.createTextNode("Brother Guo, I love you"); // There is a text node object # Guoge, I
            love you
            divObj.appendChild(textNodeObj); // < div > Brother Guo, I love you < / div >
// divObj.innerHTML = "Brother Guo, I love you"; / /< Div > Brother Guo, I love you < / div >, but it's only in memory
// Add child element
            document.body.appendChild(divObj);
        }
    </script>
</head>
<body>
</body>
</html>

(3) Common attributes of nodes

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>dom query</title>
    <link rel="stylesheet" type="text/css" href="style/css.css" />
    <script type="text/javascript">
        window.onload = function(){
//1. Find #bj nodes
            document.getElementById("btn01").onclick = function () {
                var bjObj = document.getElementById("bj");
                alert(bjObj.innerHTML);
            }
//2. Find all li nodes
            var btn02Ele = document.getElementById("btn02");
            btn02Ele.onclick = function(){
                var lis = document.getElementsByTagName("li");
                alert(lis.length)
            };
//3. Find all nodes with name=gender
            var btn03Ele = document.getElementById("btn03");
            btn03Ele.onclick = function(){
                var genders = document.getElementsByName("gender");
                alert(genders.length)
            };
//4. Find all li nodes under #city
            var btn04Ele = document.getElementById("btn04");
            btn04Ele.onclick = function(){
//1 get the node with id of city
//2. Through the city node getElementsByTagName query child nodes by tag signature
                var lis = document.getElementById("city").getElementsByTagName("li");
                alert(lis.length)
            };
//5. Return #city's all child nodes
            var btn05Ele = document.getElementById("btn05");
            btn05Ele.onclick = function(){
//1 get the node with id of city
//2 get all child nodes through city
                alert(document.getElementById("city").childNodes.length);
            };
//6. Return #phone's first child node
            var btn06Ele = document.getElementById("btn06");
            btn06Ele.onclick = function(){
// Query the node with id phone
                alert( document.getElementById("phone").firstChild.innerHTML );
            };
//7. Return #bj the parent node
            var btn07Ele = document.getElementById("btn07");
            btn07Ele.onclick = function(){
//1 query the node with id bj
                var bjObj = document.getElementById("bj");
//2 bj node get parent node
                alert( bjObj.parentNode.innerHTML );
            };
//8. Return #android's previous sibling node
            var btn08Ele = document.getElementById("btn08");
            btn08Ele.onclick = function(){
// Get the node with android id
// Get the previous sibling node through android node
                alert( document.getElementById("android").previousSibling.innerHTML );
            };
//9. Read #username's value attribute value
            var btn09Ele = document.getElementById("btn09");
            btn09Ele.onclick = function(){
                alert(document.getElementById("username").value);
            };
//10. Set #username's value attribute value
            var btn10Ele = document.getElementById("btn10");
            btn10Ele.onclick = function(){
                document.getElementById("username").value = "Brother Guo, you are so awesome";
            };
//11. Returned #bj text value
            var btn11Ele = document.getElementById("btn11");
            btn11Ele.onclick = function(){
                alert(document.getElementById("city").innerHTML);
// alert(document.getElementById("city").innerText);
            };
        };
    </script>
</head>
<body>
<div id="total">
    <div class="inner">
        <p>
            Which city do you like?
        </p>
        <ul id="city">
            <li id="bj">Beijing</li>
            <li>Shanghai</li>
            <li>Tokyo</li>
            <li>Seoul</li>
        </ul>
        <br>
        <br>
        <p>
            What kind of stand-alone game do you like?
        </p>
        <ul id="game">
            <li id="rl">Red police</li>
            <li>Actual situation</li>
            <li>Best flying car</li>
            <li>World of Warcraft</li>
        </ul>
        <br />
        <br />
        <p>
            What is the operating system of your mobile phone?
        </p>
        <ul id="phone"><li>IOS</li><li id="android">Android</li><li>Windows Phone</li></ul>
    </div>
    <div class="inner">
        gender:
        <input type="radio" name="gender" value="male"/>
        Male
        <input type="radio" name="gender" value="female"/>
        Female
        <br>
        <br>
        name:
        <input type="text" name="name" id="username" value="abcde"/>
    </div>
</div>
<div id="btnList">
    <div><button id="btn01">lookup#bj node < / button > < / div >
    <div><button id="btn02">Find all li node</button></div>
    <div><button id="btn03">lookup name=gender All nodes of</button></div>
    <div><button id="btn04">lookup#All li nodes under city < / button > < / div >
    <div><button id="btn05">return#All child nodes of city < / button > < / div >
    <div><button id="btn06">return#The first child node of the phone < / button > < / div >
    <div><button id="btn07">return#bj's parent node < / button > < / div >
    <div><button id="btn08">return#The previous brother node of android < / button > < / div >
    <div><button id="btn09">return#Value attribute value of username < / button > < / div >
    <div><button id="btn10">set up#Value attribute value of username < / button > < / div >
    <div><button id="btn11">return#bj text value < / button > < / div >
</div>
</body>
</html>

Keywords: Javascript Front-end

Added by trexx on Sat, 26 Feb 2022 10:01:51 +0200