Basic knowledge of JavaScript

1. Concept

  • A client scripting language
    • Running in client browsers, each browser has a parsing engine for JavaScript scripts
    • Scripting language: it can be parsed and executed by the browser without compiling
  • function
    • It can be used to enhance the interaction between users and html pages, control html elements and increase dynamic effects

2.ECMAScript: the standard of client script language

  • Basic grammar
    • Combine with html
      • Define < script >, and the content of the tag body is js code
      • Define < script >, and import the external js file through src attribute
      • < script > can be defined anywhere on the html page, but the definition location will affect the order of execution
      • < script > can define multiple

3. Data type

  • JavaScript raw value

Raw values are values that have no properties or methods.

The original data type refers to the data that has the original value.

JavaScript defines five types of raw data:

  • string
  • Number: number, NaN
  • boolean
  • null: space occupation
  • undefined

The original values are immutable (they are hard coded and therefore cannot be changed).

Assuming x = 3.14, the value of X can be changed. However, you cannot change the value of 3.14.

  • Key words: var is a local variable, not a global variable

  • character string

  • array

    • Can contain any data type

    • Variable array size

    • push pushes into the tail, pop pops up an element of the tail (similar to stack)

    • unshift press in the head and shift eject the head

    • concat() returns a new array without changing the original array

  • object

    • var Object name = {
          Attribute name: attribute value,
          Attribute name: attribute value,
          Attribute name: attribute value
      }//Separated by commas, the last key value pair does not need parentheses, and the key is a string
    • Using a nonexistent object attribute will not report an error, undefined

    • You can dynamically delete attributes

      delete Object name.Attribute name //Delete attribute
       Object name.Attribute name=value //Add attribute
  • Process control

    • if,while,for,switch

    • for/in traverses the object key, and for/of traverses the object value

      var person = {fname:"Bill", lname:"Gates", age:62}; 
      var text = "";
      var x;
      for (x in person) {
          text += person[x];
  • Map/Set

    var map = new Map([key,value],[key,value],[key,value]);
    map.get("key") //Value 
    map.set("key",value) //Stored value
    var set = new Set([value,value,value]);
    set.has(value) //Determine whether to include
  • Function object

    • Creation method:

      //Parameter types need not be written
      function Method name(Formal parameter list){
          //Method body
          //There is no need to define the return value type
      var Method name = function(Formal parameter list){
          //Method body
    • Method is an object. If you define a method with the same name, it will be overwritten.

    • The call of a method is only related to the name of the method, not the parameter list.

      function fun(a,b){
      fun(1) //In this case, b is undefind
      fun(1,2,3,4) //In the method declaration, there is a hidden built-in object (array), arguments, which encapsulates all the actual parameters. 3 and 4 are received by it.
      //An example of using built-in objects
      function add(){
          var sum=0;
          for(var i=0;i<arguments.length;i++){
              sum += arguments[i];
          return sum;
  • Date Date object

    var date = new Date(); //Create a time zone for the current browser and display the date as a full text string
    //Fri Oct 23 2020 11:12:25 GMT+0800 (China standard time)
  • Global object

    • encodeURL()

      • url encoding: encode the corresponding string into the hexadecimal code in the format specified by the page

      • "How are you?"% E4%BD%A0%E5%A5%BD%E5%90%97%EF%BC%9F

    • dedecodeURL()

      • url decoding
    • encodeURLComponent()

      • More characters than the above encoding / decoding
    • deencodeURLComponent()

    • parseInt()

      • Parse a string and convert it to a number
    • isNaN ()

      • Check if it is not a number
    • eval()

      • Parsing a string into script code execution


  • Concept: Document Object Model document object model encapsulates all components of markup language documents as objects, which can be used to add, delete, modify and query documents dynamically.

    • DOM tree, corresponding to the structure of HTML document

    • Including: Core DOM - standard model for all document types
      XML DOM - standard model for XML documents
      HTML DOM - standard model for HTML documents

  • document object

    • Get Element object:

      • getElementById(): find the element with the specified unique ID

      • getElementsByTagName(): returns all element nodes with the specified tag name, and the return value is an array

      • getElementsByNam(): returns all element nodes with the specified Name attribute, and the return value is an array

      • getElementsByClassName(): returns all element nodes with the specified Class attribute. The return value is an array

      • Code: get page label object Element

          document.getElementById("test") //The specified tag is obtained from the id value of the element (tag) 		 sign
    • Create additional DOM objects:

      • createAttribute(name) Create an attribute node with the specified name and return a new Attr object

      • createComment() Create annotation node

      • createElement() Create element node

        var table = document.createElement("table")
      • createTextNode() Create text node

    • Action label object

      • Modify attribute value

      • Modify label body content

  • Element object:

    • Get / create method: get and create through documen t

    • method:

      • setAttribute()

        elementNode.setAttribute(name,value) //name 	 Required. Specifies the property name value to be set 	 Required. Specifies the property value to set.
      • removeAttribute()

        elementNode.removeAttribute(name) //name 	 Required. Specifies the attribute name to delete
  • Node object:

    • Features: all other DOM objects can be considered as a node

    • Method: add, delete, modify and query DOM tree:

      • appendChild() adds a new child node to the end of the node's child node list

      • removeChild() Deletes (and returns) the specified child node of the current node

        var div1 = getElementById("div1");
        var div2 = getElementById("div2");
      • replaceChild() Replace a child node with a new node

    • Properties:

      • parentNode Returns the parent node of the node

      • childNodes Returns the list of nodes from node to child node

        var x=nodeObject.childNodes;
        for (i=0;i<x.length;i++)

    • Tag body setting and acquisition: innerHTML

      /*The easiest way to modify the content of an HTML document is to use the innerHTML attribute.
      To modify the content of an HTML element, use this syntax:*/
      document.getElementById(id).innerHTML = new text
    • Objects and attributes using HTML elements:

      document.getElementById(id).attribute = new value //Attribute attribute, value value
      <!--This example modifies <img> Elemental src The value of the property-->
      <img id="myImage" src="smiley.gif">
      document.getElementById("myImage").src = "landscape.jpg";
    • Set style:

    • Method 1:

      document.getElementById(id) = new style
      <p id="p2">Hello World!</p>
      document.getElementById("p2").style.color = "blue";
    • Method 2:

          //css style control

5. Events

  • Function: HTML events can be something done by browsers or users:

    • Here are some examples of HTML events:

      • HTML page finished loading
      • HTML input field modified
      • HTML button clicked

      Usually, when an event occurs, the user will want to do something. JavaScript allows code execution when the event is detected.

    • With JavaScript code, HTML allows you to add event handlers to HTML elements.

  • Event source: component, such as button, text input box

  • Event binding / registration:

    • Directly on the html page, specify the attribute (operation) of the event, and the attribute value is js code

      <button onclick="displayDate()">What's the time?</button>
      function displayDate() {
          document.getElementById("demo").innerHTML = Date();
      //Code coupling is too high
    • Get the element object through js, specify the event attribute and set a function

      <img src="#" id=image>
      var object = getElementById("image");
      function fun(){
  • Common events:

    • Click event:

      • onclick The event handle called when the user clicks on an object
      • ondblclick The event handle called when the user double clicks an object
    • Focus event:

      • onblur Element loses focus

        • Generally used for form verification
      • onfocus Element gets focus

    • Load event:

      • onload A page or an image is loaded

        • Can be bound with window
    • Mouse events:

      • onmousedown Mouse button pressed
        • A parameter will be passed, and a formal parameter will be defined when defining the method to indicate which mouse button is clicked
      • ,onmouseup Mouse button released
      • onmousemove Mouse moved
      • onmouseout Move the mouse away from an element
      • onmouseover Move the mouse over an element
    • Keyboard events:

      • onkeydown A keyboard key is pressed
      • onkeypress A keyboard key is pressed and released
      • onkeyup A keyboard key is released
    • Select and change:

      • onchange The content of the domain is changed
      • onselect Text selected
    • Form Events

      • onsubmit The confirm button is clicked

        • Only the form form is supported. If it returns true, it will be submitted. Note whether return needs to be added here. Return is required for method 1 and not for method 2 of event registration.
      • onreset Reset button clicked


  • Concept: Browser object model

    • Encapsulate browser components into objects

      • 1.window: browser window object
        • Features: window does not need to be created and can be used directly

        • window. Method name (), window can be omitted directly

        • Methods related to pop ups:

          alert()		//Displays a warning box with a message and a confirmation button
          confirm()		//Displays a warning box with a message and confirm and Cancel buttons, with a return value of boolean type
          prompt()		//Displays a dialog box prompting the user for input, with a return value
        • Windows related to development closure:

          open()		//Open a new window
          close()		//Close the window that has been opened. Who calls to close who
        • Methods related to timer:

          setTimeout(code,millisec)		//Code: the JavaScript code string to be executed after the function to be called; millise: the number of milliseconds to wait before executing the code. The return value is a unique ID, which is used to cancel the timing.
          clearTimeout(id_of_settimeout)		//id_of_settimeout: ID value returned by setTimeout(). This value identifies the delayed execution code block to cancel.
          setInterval(code,millisec)		//Code: the JavaScript code string to be executed after the function to be called; millise: the number of milliseconds to wait before executing code. The setinterval () method keeps calling the function until clearinterval () is called or the window is closed. The ID value returned by setInterval() can be used as an argument to the clearInterval() method.
          clearInterval()		//Cancels the timeout set by setInterval().
        • Get other BOM objects

          history		//window can be omitted directly
        • Get DOM object

      • 2.location: address bar object
        • Properties:

          • The href attribute is a readable and writable string that sets or returns the full URL of the currently displayed document.

              location.href //Get the value of the current address bar, or set the value of the current address bar
          • The reload() method is used to reload the current document

          location.reload(force) // If the parameter is false, it will use the HTTP header if modified since to detect whether the document on the server has changed. If the document has changed, reload() downloads the document again. If the document does not change, the method loads the document from the cache. If the parameter of this method is set to true, it will bypass the cache and re download the document from the server no matter what the last modification date of the document is.

      • History: history object

      • Screen: display screen object

      • Navigator: Browser Objects

Posted by chetan1 on Tue, 10 May 2022 14:33:03 +0300