JavaScript learning notes

Posted by shrive22 on Sun, 27 Feb 2022 02:44:19 +0100

1, Overview
JavaScript is a scripting language. Its target program is saved in the form of ordinary text. JS runs in the browser, which has a kernel that executes JS code. It has nothing to do with JAVA.
JavaScript is mainly used to operate nodes in HTML to produce dynamic effects. It is a programming language.
Core syntax: ECMAScript
2, How to embed JS code
The first type: inter line event.

<html>
    <head>
    </head>
    <body>
        <!--1,The user clicks the button to display the dialog box
            2,Java It is an event driven programming language. It usually executes a piece of code when an event occurs. stay JS In, events will correspond to event handles
            3,All event handles exist in the form of tag attributes.
            As long as a user clicks the button object below, a mouse click event occurs on the button object. So register in onclick Events in the handle JS code
            Will be executed. onclick The latter code is actually executed by the browser.
            4,onclick The following code is not executed when the browser is open. Wait for the of the button click The incident occurred,
            As soon as it happens, the following code is called by the listener
            5,stay JS There is a built-in BOM Object, which can be used directly, all in lowercase: window
            among window Object has a method (function) called alert,This function is specially used to pop up the dialog box.
            6,JS Code can end with or without a semicolon.
            7,window Can be omitted
    -->
        <input type="button"  value="xiaoke"   onclick="window.alert('I love Xiao Ke');" />
        <input type="button"  value="xiaoke2"   onclick="alert('I love Xiaoke 2');" />
    </body>
</html>

Second: script block mode.

<html>
 <head>


 </head>
 <body>
     <script type="text/javascript">
/*Write JS code directly here. These codes are executed from top to bottom when the page is opened*/
       alert('hello Kero');
       alert('hello kero 2');
       alert('hello kero 3');


     </script>
 </body>


</html>

The third kind: introduce external independent JS files

<script type="text/javascript" src="js/xxx.js">
     </script>
xxx.js representative JS File name.

Identifier naming rules and specifications are implemented in Java.
3, Variables in JS
Declaration: var variable name;
Assignment: variable name = value;
JS language is a weakly typed language. There is no compilation stage. You can directly open the browser to open interpretation and execution. When declaring variables in JS, you do not need to specify the data type of variables. During the running process of the program, what type of value is assigned to the variables is what data type, and the data type of variables can be changed.
Global variable: a variable declared outside the body of a function. Global variables allocate space when the browser is open and destroy it when the browser is closed.
Local variable: a variable declared in the body of a function. Local variables allocate space when the function is called. After the function is executed, the memory is released.
4, Function

<html>
 <head></head>
 <body>
     <script type="text/javascript" >
       /*  
       Function definition syntax format:
       function Function name (formal parameter list){
           Function body;
       }
        Example: function sun(a,b){
            return a+b;
        }
        Equivalent to:
        sun=function(a,b){
            return a+b;
        }
       */
    function sun(a,b){
            alert(a+','+b);
        }
        sun(1,2);
     </script>
 </body>


</html>

Functions in JS cannot be overloaded. As long as a function with the same name appears, the previous function disappears.
5, JS data type
typeof operator: it can dynamically obtain the data type of variables during the running of JS code.
Syntax format: typeof variable name;
The operation result is one of the following six strings: undefined,boolean,string,number,object,function.
JS to judge whether two strings are equal, use '= ='.
Undefined type: there is only one value, which is undefined. When the declared variable has no assignment, the system defaults to undefined.
Null type: there is only one value, which is null. The result of typeof null operation is: object.
Number type: it belongs to the original type. Both integer and floating-point numbers belong to number, Nan (indicating that it is not a number) and Infinity. There is a function called isNaN(). The final return type of this function is Boolean. Returning false means it is a number, and returning true means it is not a number. There is also a function called number (), which can convert non numeric data into numeric data. The parseint() function can convert a string to a number and only round the digits, which can be used to round down.
boolean type: it belongs to the original type and has only two values, true and false. There is a function called Boolean(), which can convert variables that are not boolean types into boolean types.
String type: it belongs to the original type. There are two ways to define string type: var s = "string"; var s = new string("string");
The length attribute can obtain the length of the string;
Object type: object type can be regarded as the superclass of all objects. It is the type defined by default in JS. If there is no special description, it inherits object by default. The prototype attribute can dynamically extend attributes and methods to objects.
How to define class new object calling methods in JS: there are two ways to define classes:
1. function class name (formal parameter list){
this. Attribute name = parameter;
this. Method name = function() {}
}
2. Class name = function (formal parameter list){
this. Attribute name = parameter;
this. Method name = function() {}
}

<html>
<head></head>
<body>
<script type="text/javascript" >
    function emp(x,y,z){
        //attribute
        this.empno=x;
        this.ename=y;
        this.sal=z;
         //method
        this.work=function(){
            console.log(this.ename+"is working");
        }
    }
    //create object
    var e = new emp();
    e.work();
    var e2 = new emp(111);
    e2.work();
    var e3 = new emp(2222,"king");
    e3.work();
    var e4 = new emp (333,'S',800)
    //Dynamic extension method for emp
    emp.prototype.getSal = function(){
        return this.sal;
    }
    console.log(e4.getSal());
</script>
</body>
</html>

==, only compare values for equality
===, compare both values and data types for equality
6, Events
blur: lose focus
Focus: get focus

Click: mouse click
dbclick: double click

keydown: keyboard press
keyup: keyboard pops up

mousedown: mouse down
mouseover: mouse over
mousemove: mouse movement
mouseout: mouse out
mouseup: mouse up

submit: form submission
Reset: form reset

select: the text is selected
change: the item in the drop-down list changes or the content of the text box changes
load: the page is loaded
Any event has a corresponding event handle. The event handle adds on before the event name.

<html>
<head>
    <style type="text/css">
 input{
     border: 1px solid black;
     width: 300px;
}
    </style>
</head>
<body>
<script type="text/javascript" >
</script>

Test focus loss event: < input type = "text" onblur = "console. Log ('lost ')" / >;
Test get focus event: < input type = "text" onfocus = "console. Log ('Get ')" / >;
Test click event: < input type = "button" value = "click" onclick = "console. Log ('click ')" / >;
Test dbclick event: < input type = "button" value = "dbclick" ondbllick = "console. Log ('double click ')" >;

</body>
</html>

The first method of event registration:

<html>
<head>
    <style type="text/css">
  
    </style>
</head>
<body>
<script type="text/javascript" >
  function sayhello(){
      console.log("hello kero")
  }
</script>
  <!--This way of registering events is the first way. Use the event handle in the tag and write after the event handle JS Code, after the event corresponding to the event handle occurs
 The code registered in the event handle is called.
onclick Only when click After the event, register in onclick The resulting code will be executed.
-->
    <input type="button" value="hello kero" onclick="sayhello()"/>
</body>
</html>
The second way:
<html>
<head>
    <style type="text/css">
  
    </style>
</head>
<body>
    <input type="button" value="hello" id="hellobtn" onclick="" >
<script type="text/javascript" >
    function sum(){
        console.log("sum");
    }
/*Get button object based on id*/
         var hellobtnElt = document.getElementById("hellobtn");
        //You can point to any attribute of an element
        /* This line of code will be executed when the page is opened. The meaning of this line of code is to bind the callback function of sum to the click event of hellobtn*/
        
        hellobtnElt.onclick = sum;
 
</script>
</body>

</html>
Event case:
<html>
<head>
</head>
<body>    
<script type="text/javascript" >
  window.onload = function(){
      //Bind a mouse click to the element with id="btn1"
      var btn1Elt=document.getElementById("btn1");
    btn1Elt.onclick = function(){
        console.log("1 Be clicked");
    }
    //Bind a mouse click to the element with id="btn2"
    var btn2Elt=document.getElementById("btn2");
    btn2Elt.onclick = function(){
        console.log("2 Be clicked");
    }
  } 
</script>
   <input type="button" id="btn1" value="button1"/>
   <input type="button" id="btn2" value="button2"/>
</body>
</html>

7, void operator, JS control statement, built-in object
Syntax format: void (expression)
Executing an expression does not return any result. Even if the expression has an execution result, it will have nothing after void.
Select structure: if, switch
Loop structure: for, while, do... While
Turn statements: break,continue,return
JS special statements (not commonly used):
for... in statement
with statement

<html>
<head>
</head>
<body>
<script type="text/javascript" >
    //The array is built using brackets
  var arr = [1,24,5,65,76,7];
  //for....in statement
   for(var index in arr){
       //index is the subscript in the array element
       console.log(index);
       //console.log(arr[index]);
   }
   //for... The in statement can also take the attribute value of the object
   Employee = function(empno,ename){
       this.empno=empno;
       this.ename=ename;
   }
   var e = new Employee(700,'kero');
   console.log(e.empno+','+e.ename);


</script>
</body>
</html>
Built in object array:
<html>
<head>
</head>
<body>
<script type="text/javascript" >
 /*
 1,How to create an array object
 2,How to traverse an array
 3,How to modify an element in an array
 4,How to read an element in an array 
 */
//The first way to create an array
var a=[1,2,3,4,5];
//The second way to create an array
var arr= new Array(5);//Create an array of length 5
var arr2 = new Array(1,2,3,4,5);
</script>
</body>
</html>
Add element: array name.push(Add element)And is added to the end.
pop(): Pop up the elements at the end of the array and reduce the length by one.
reverse(): Flip the array.
Built in object date:
var time =new Date();

8, DOM programming case
BOM is the browser object model: the operation of the browser window can be completed through the objects and methods of BOM. The top-level built-in object is window.
DOM is a document object model: through DOM objects and methods, you can complete the addition, deletion and modification of elements in web pages and produce dynamic effects. The top-level built-in object is document.
The difference between innerHTML and innerText:

<html>
<head>
  <style type="text/css">
 #div1{
     background-color: antiquewhite;
     border: 1px solid red;
     width: 200px;
 }


  </style>
</head>
<body>
    <script type="text/javascript">
    window.onload = function(){
        document.getElementById("btn").onclick = function(){
            //Set the content in div
           var divElt= document.getElementById("div1");
           //Set the internal content through the innerHTML attribute of the element
           //Innergroup will interpret the HTML as a string and execute the following HTML attribute
           //divElt. InnerHTML = "< font color = 'Red' > user name cannot be empty < / font >";
           //innerText will be regarded as an ordinary string and will not be interpreted and executed.
           divElt.innerText = "<font color ='red'>  User name cannot be empty</font>";
        }
    }    
    </script>
    <input type="button" id="btn" value="ssss"/>
<div id="div1">
</div>
<span id="span1">
</span>
</body>
</html>
Select all and deselect all check boxes:
<html>
<head>
  <style type="text/css">
  </style>
</head>
<body>
    <script type="text/javascript" >
        window.onload = function(){
            //Bind click to the id="firstChk" element
           var firstChkElt= document.getElementById("firstChk");
           firstChkElt.onclick = function(){
              //Get all check box objects
              var vtb = document.getElementsByName("vtb");
              if(firstChkElt.checked){
//Traversal array
for(var i =0 ;i<vtb.length;i++){
                  var vtbChk = vtb[i];
                  vtbChk.checked = true
              }
              }else{
                  //Traversal array
              for(var i =0 ;i<vtb.length;i++){
                  var vtbChk = vtb[i];
                  vtbChk.checked = false;
              }
              }
           }
        }
    </script>
    <input type="checkbox" id="firstChk">
    <br>
    <input type="checkbox" name="vtb" value="xiaoke"/>xiaoke
    <br>
    <input type="checkbox" name="vtb" value="az"/>az
    <br>
    <input type="checkbox" name="vtb" value="nanami"/>nanami
    <br>
</span>
</body>
</html>
Gets the of the text box value: 
<html>
<head>
  <style type="text/css">
  </style>
</head>
<body>
    <script type="text/javascript" >
 window.onload= function(){
     document.getElementById("btn").onclick = function(){
         //Get text box object
         var usernameElt =document.getElementById("username");
         //Get value
         var username = usernameElt.value;
         alert(username);
     }
 }
    </script>
    user name:<input type="text" id="username"/>
    <br>
    <input type="button" id="btn" value="xiaoke">
</span>
</body>
</html>
Gets the name of the selected item in the drop-down list value: 
<html>
<head>
  <style type="text/css">
  </style>
</head>
<body>
  <select id="iiii" onchange="alert(this.value)"><!--Represents the current drop-down list object-->
      <option value="">number</option>
      <option value="001">1111</option>
      <option value="002">2222</option>
      <option value="003">3333</option>
      <option value="004">4444</option>
  </select>


    <script type="text/javascript">
        window.onload = function(){
            document.getElementById("iiii2").onchange = function(){
                alert(this.value)
            }
        }
    </script>


  <select id="iiii2" >
    <option value="">number</option>
    <option value="001">1111</option>
    <option value="002">2222</option>
    <option value="003">3333</option>
    <option value="004">4444</option>
</select>
</span>
</body>
</html>
Call function and web page clock periodically:
<html>
<head>
  <style type="text/css">
  </style>
</head>
<body>
<script type="text/javascript">
    window.onload = function(){
    document.getElementById("displayTimeBtn").onclick= function(){
        //The return value is a value that can cancel the periodic call
      v= window.setInterval("displayTime()",100)
    }
    document.getElementById("stoptimeBtn").onclick= function(){
       window.clearInterval(v);
    }
    }
  function displayTime(){
       //Get the current time of the system and display the time in div
       var nowTime = new Date();
        //Display to div
        document.getElementById("timediv").innerHTML = nowTime.toLocaleString();
  }


    //window.setInterval("display()",100);
</script>


<input type="button" value="showtime" id="displayTimeBtn">
<input type="button" value="stop" id="stoptimeBtn">
<div id="timediv" ></div>
</body>
</html>

9, BOM programming case
Opening and closing of windows:

<html>
<head>


</head>
<body>


     <input type="button" value="Open Baidu" onclick="window.open('http://www.baidu.com')"/>
     <input type="button" value="Open Baidu 2" onclick="window.open('http://www.baidu.com' ,'_self')"/>


     <input type="button" value="close window" onclick="window.close()"/>


</body>
</html>

alert and confirm:
alert: pop up message box
confirm: a confirmation box pops up
10, JSON

<html>
<head>
</head>
<body>
    <script type="text/javascript">
        /*
        1,JSON: JavaScript Object Notation(JavaScript Tag object)
        Is a lightweight data exchange format.
        The volume is small, but there can be a lot of data.
        JSON And XML are standard data exchange formats. XML is bulky and difficult to parse. JSON syntax is relatively loose.
        2,In JavaScript, JSON exists as an object
        3,Define JSON format objects in JavaScript:
        Syntax format:
        var jsonObj = {
            "Attribute name ": attribute value,
            "Attribute name ": attribute value,
            "Attribute name ": attribute value,
            "Attribute name ": attribute value,
            ......
        };
        */
  var emp = {
      "empno":7379,
      "ename":"xiaoke",
      "sal":9999
  };
  //How to access object properties
  console.log(emp.empno)//The first way
  console.log(emp["empno"])//The second way
  
    </script>
</body>


</html>

1. How do Java and JavaScript exchange data?
You can use a string in JSON format.
2. JDBC connects to the database to query the data, and then splices the data into a string in JSON format.
Pass the JSON format string to JavaScript, and then convert the JSON format string into JSON object in JavaScript to complete the data exchange.


Topics: Javascript Front-end JSON html