WEB front-end-javescript study notes (7)

1. Built-in objects
    1) Global objects
        There is no global object in JS, and Web browsers implement Global as part of the window object.

        Method:
            a.encodeURIComponent(): encode unicode
            b.decodeURIComponent(): decode unicode encoding
            c.eval(''): has the function of string parser (use with caution! Because its performance is poor , and more dangerous)
    2) Math object
        This object mainly provides a large number of properties and methods of mathematical operations.
        Attribute:
            Math.E
            Math.PI
        Method:
            Math.min(): take minimum function
            Math.max(): take maximum value function
            Math.round(): round function
            Math.ceil(): round up (take greater than or equal to the smallest integer of the operand)
            Math.floor(): Round down (take the largest integer less than or equal to the operand)
            Math.random(): Generate an arbitrary decimal between [0,1)
            Math.abs (num): Returns the absolute value of num
            Math.exp(num): Returns the num power of Math.E
            Math.log(num): Returns the natural logarithm of num
            Math.pow(num,power): Returns the power of num
            Math.sqrt(num): Returns the square root of num
            Math.acos(x): Returns the inverse of x Cosine
            Math.asin(x): Returns the arc sine of x
            Math.atan(x): Returns the arc tangent of x
            Math.atan2(y,x): Returns the arc tangent of y/x
            Math.cos(x ): Returns the cosine value of x
            Math.sin(x): Returns the sine value of x
            Math.tan(x): Returns the tangent value of x
2. Object-oriented
    object creation:
        1) Conventional creation
            a.new
            b. Literal value
        2 ) The factory pattern
            creates a batch of similar objects by encapsulating functions.
            Defect: It is impossible to know which object instance the created object is.
        3) Constructor
            The constructor is used to build a class (there is no concept of class in ES5, in fact the constructor here is a class).
            A class is an abstract symbolic representation of an object (a class is formed by extracting the same or similar part of the object).
            An object is an instantiation (reification) of a class (endowed with certain attributes and functions)

            a. Creating a constructor (class)
                Syntax:
                    function class name ([formal parameter list]) {                         this. attribute name = parameter;                         ...                         this. method name = function () {                             function body;                         }                         ...                     }             b. By constructing function instantiation object                 new class name([argument list]);








            The difference between the method using the constructor and the method using the factory pattern is as follows:
                • The constructor method does not explicitly create an object (new Object());
                • Directly assign properties and methods to this object;
                • There is no return statement.
            There are some specifications for the method of the constructor:
                • The function name and the instantiated constructor name are the same and capitalized, (PS: not mandatory, but writing in this way helps to distinguish the constructor from ordinary functions); • The
                new operator must be used to create an object through a constructor symbol.
           The process of the constructor execution:
                • When the constructor is used, and the new constructor (), then the new Object () is executed in the background; •
                The scope of the constructor is given to the new object, (that is, the one created by new Object () object), and this in the function body represents
                the object from new Object().
                • Execute the code in the constructor;
                • Return a new object (return directly in the background).
3. Basic packaging types
    There are three special classes in the basic data types: String, Number and Boolean.
    The above three basic types have their own packaging objects with corresponding properties and methods. The process of calling the method happens in the background, so we call it the basic wrapper type.

    In layman's terms, the basic types of data have a class that wraps them. These classes have their own attributes and methods, and these basic types of data can directly call these attributes and methods.

    1) The Boolean type
        does not have its own properties and methods.
    2) Number type
        a. The attribute
            MAX_VALUE indicates the maximum number
            MIN_VALUE indicates the minimum value
            NaN, non-numeric value
            NEGATIVE_INFINITY negative infinity, overflow returns the value
            POSITIVE_INFINITY infinity, overflow returns the value
            prototype prototype, used to add new properties and methods
        b. method
            toString() will The value is converted into a string, and can be converted into a
            base. toLocaleString() Converts to a string according to the local number format
            toFixed() Retains the specified number of digits after the decimal point and converts it to a string
            toExponential() Represents the number in exponential form, retaining the decimal point Then specify the number of digits and convert it into a string.
            toPrecision() Express the number in exponential form or dot form, keep the specified number of digits after the decimal point and convert it into a string
            valueOf() Display the original value
    3) String type
        a. attribute
            length
        b. The method
          str.charAt(n) returns the character at the specified index position
          str.charCodeAt(n) returns the character at the specified index position in Unicode encoding
          str.concat(str1...str2) Concatenates the string parameters to call this method The string
          str.slice(n,m) returns the string
          str.substring(n,m) returns the string str.substr(n,m) between the string n and
          m ) returns m strings starting from string n
          str.indexOf(str, n) the first str searched from n, and returns the searched index value
          str.lastIndexOf(str, n) the last searched from n A str, and return the searched index value
          str.str.toLowerCase() Convert all strings to lowercase
          str.str.toUpperCase() Convert all strings to uppercase
          str.match(pattern) Return the substring in pattern or null
          str.replace(pattern, replacement) replace pattern with replacement
          str.search(pattern) returns the starting position of pattern in the string
          str.split(pattern) Returns an array of strings split according to the specified pattern
          String.fromCharCode(ascii) Static method, outputs the value corresponding to the Ascii code
          str.localeCompare(str1,str2) Compares two strings and returns the corresponding value
4 . Variables, scope and memory
    1) Variables
        a. Variables of basic types
            The values ​​of variables of basic types are stored in the stack. The value of a variable can be directly obtained through the variable name.
        b. Variables of reference type
            The value of a variable of reference type is stored in the heap, and the address (pointer) of the variable of reference type is stored in the stack.
            If you want to get the value of a reference type variable, you need to get the address from the stack first, and then search by address to get the value.
    2) Scope
        ES5 scope is divided into global scope and local scope.
        ES6 scope is divided into three types: global scope, local scope and block scope.
            Global scope:
                Variables defined outside a function have global scope.
            Local scope:
                Variables defined inside functions have local scope.
    3) Garbage collection mechanism
        JS has the function of automatically recycling garbage.
        During project development, when initializing an object, it is best to assign the initial value to null.

5.JSON
    JSON (JavaScript Object Natation: JS Object Notation) is a lightweight data exchange format. Store and represent data in a textual format independent of a programming language.
    1) Advantages
        : Easy to read and write, easy for browsers to parse and generate, and effectively improve network transmission efficiency.
    2) Compared with XML,
        JSON is an object when writing or parsing, which is easier to parse; while XML stores data by user-defined tags, which is not easy to write and difficult to parse for the front end.
    3) The content of the JSON file
        can be a single value, an object, an array, or a combination of an object and an array.
    4) Where to write JSON
        can be written in JavaScript code, or form an independent .json text file.
        a. When writing JSON data values ​​in JS,
            if they are strings, they can be enclosed in single or double quotation marks. Numerical data, logical values, and null cannot be enclosed in quotation marks;
            if they are objects, keys can be enclosed in single or double quotation marks. Can be left without quotes.
        b. Independent JSON file
            i) The extension of the file must be .json, the JSON file is not a JS file, and any JS code cannot appear, it is just a text file; ii)
            Data cannot be assigned to a variable;
            iii) Keys must be enclosed in double quotes;
            iv) If the value is character data, it must be enclosed in double quotation marks, and other types of data cannot be enclosed in quotation marks;
            v) No comments can be added in the JSON file.
    5) The data value can have the following three types
        ① simple value: strings, numbers, Boolean values ​​and null can be represented in JSON. But JSON doesn't support the special undefined in JavaScript.
        ②Object ({})
        ③Array ([])
    6) Data processing in actual development In actual
        project development, if the background engineer has not created the background data interface, the front-end engineer can do data mock first, Write the corresponding HTML, CSS and JS codes,
    and then replace them when the background data can be called.
        In project development, it is best to separate the data and form a separate JSON file.
    7) Parsing JSON data
        a) If JSON in JS
            is JSON data, it can be accessed directly; if it is a string in JSON format, it needs to be converted with the JSON.parse() method.

            JSON.parse(): Convert a string in JSON format to JSON
            JSON.stringify(): Convert JSON to a string in JSON format
        b) Parsing JSON files
            JSON files must be obtained using ajax (asynchronous request) technology.
6. Ajax request operation steps:
    1) Create a request object
      var xhr = new XMLHttpRequest();
    2) Establish a request connection
      xhr.open('get',url,true);// get/post: request method true/false: true indicates asynchronous request, false indicates synchronous operation url: indicates the path of the request
    4) The front end processes the result of the request
      xhr.onreadystatechange = function () {         if(xhr.readyState == 4 && xhr.status == 200){ / / If the request is successful           console.log(JSON.parse(xhr.responseText)); // responseTextr: Get the result of the request         }       };      3) Send the request to the background       xhr.send();





    Note: If you send an ajax request, you must start the file in http (server-side), and you cannot open it locally.
7. DOM operation
    DOM (Document Object Model: Document Object Model): It is a programming interface for HTML and XML documents, and defines a standard method for accessing and manipulating HTML and XML documents.
    DOM expresses HTML and XML documents in a tree directory structure, and each node is a DOM element.
        document->html->head/body->...
    1) DOM node
        a) Node hierarchy The node
            hierarchy is divided into parent-child nodes and sibling nodes.
                In a node tree, the top node is called the root.
                Every node has a parent, except the root (which has no parent).
                A node can have any number of children.
                Sibling nodes are nodes that have the same parent, and Called sibling node
        b) DOM node classification
            element node: label
            attribute node: label attribute
            text node: newline after label document
            node: document
        c) DOM node name (nodeName)
            element node label name is the same
            Attribute node attribute name is the same
            text node #text
            document node #document
        d) DOM node value (nodeValue)
            element node undefined or null
            attribute node attribute value
            text node text content
        e) DOM node type (nodeType)
            element 1
            attribute 2
            text 3
            Note 8
            Document 9
    2) Node operation
        a) Get node
            Get node by ID [return a specific node]
                document.getElementById(ID name)
            get node by tag name [return node array, even if there is only one]
                document.getElementsByTagName(tag name )
            Get the node through the name value of the label [return node array]
                document.getElementsByName(Name)
            Get nodes by class value [return node array]
                document.getElementsByClassName(Class name)
            returns the first document in the found result set according to the selector
                . querySelect("selector")
            returns the found result set according to the selector, which is an array of nodes
                document.querySelectAll("Selector")
        b) Create a DOM node
            i) Create an element node
                document.createElement('tag name');
            ii) Create a text node
                document.createTextNode('Text content');
            iii) Create an attribute node
                document .createAttribute('attribute name');
                attribute node name.value = 'attribute value'; // set the value for the attribute

              //Associate the above three nodes
              element node name.appendChild(text node name); //add text node
              element node name to element node.setAttributeNode(attribute node name); //add attribute node to element node

              document.body.appendChild(element node name); // Add the created node to the document


        Concise writing:
            var oDiv = document.createElement('div'); // create element node
            oDiv.setAttribute('class','wrapper box'); // add attribute and attribute value for element node
            oDiv.innerHTML = 'create Concise writing of DOM elements'; // Set the text content for the element node
            document.body.appendChild(oDiv); //Add the created element node to the document
    3) Insert node
        i) Insert the inner tail
            parent node.appendChild( Created node)
        ii) Insert an internal previous
            parent node.insertBefore(created node, known child node)
    4) Replace node
        parent node.replaceChild(new node, old node)
    5) Clone node
      deep clone: ​​contains Child nodes are cloned together.
      Shallow clone: ​​only the found node will be cloned, and the child nodes will not be cloned

        The node that needs to be copied. cloneNode(true/false);
            true: copy the current node and all child nodes (deep clone)
            false: copy only the current node (shallow clone)
    6) delete node
        i) delete the current node and child nodes
            . remove();
        ii) delete child node
            parent node.removeChild(child node)
    7) node attribute operation
        i) get attribute value
            DOM node. attribute name // cannot get user-defined attribute value
            DOM node.getAttribute(attribute name) // Get the value of all attributes (user-defined attributes)
        ii) Set the attribute value
            DOM node. attribute name = attribute value // cannot set the value of user-defined attribute
            DOM node.setAttribute(attribute name, attribute value) // set Values ​​of all attributes (user-defined attributes)
        iii) Delete attribute value
            DOM node.Attribute name = '' // cannot delete user-defined attribute
            DOM nodes.removeAttribute(attribute name) // delete all attributes (user-defined attributes)
    8) Node text operation
        i) Get the text
            node.innerHTML //Get all the content under the node including the label
            node.innerText // Get the text content under the node, and filter out the label
            node.value // Get the content
            node of the input box and other form controls. getAttribute(“value”) //value is the attribute of the form input box, you can use getAttribute to get the value
        ii) set the text
            node.innerHTML= "text content" // will translate the html tag
            node.innerText = "text content" // Will not translate html tag
            nodes.value = value
            node.setAttribute("value",value) // Because value is an attribute, you can also set the content in this method
        iii) delete the text
            node.innerHTML= ""
            node.innerText = " "
            Node.value = ""
            Node.removeAttribute("value")
    9) DOM node style operation
        a) Operation style class
            i) Get the class
                node.className Get all the class
                nodes of the node.getAttribute("class") Get all the classes of the node
            ii) Set the class
                node.className = value
                node.setAttribute("class",value)
            iii)Other method
                nodes. classList.add(value); //add the specified class
                node to the element.classList.contains(value); //determine whether the element contains the specified class, if it exists return true
                node.classList.remove(value); //delete Specified class
                node.classList.toggle(value); // If there is, delete it, if not, add the specified class
        b) Operate the inline style
            i) Get the inline
                style node.style. Style attribute name // Get a specific content Inline
                style node.style.cssText // Get all inline styles of a node and return a string
            ii) Set inline styles
                Node.style.Style attribute name = attribute value // Set a specific inline
                style Node.style.cssText = attribute value or attribute value list // Set all inline styles of a node
8. Common events
    onload onclick ondblclick onmouseover onmouseout onmousemove onmousedown onmouseout onblur onfocus onsubmit onrest onchange
    onkeydown onkeyup onkeypress
    onresize
    ...

9. Know jQuery
    JQ is a JS library, which is a package of JavaScript, that is to say, JQ provides a large number of APIs, and realizes the most functions with the least code during development.
    Open source in 2006, it has now developed into a powerful framework system integrating JS, CSS, DOM, and Ajax.
    Purpose: write less, do more! (Write less, do more)
10. Learning documents
    Chinese documents: https://www.jquery123.com/
    API learning or query: https://jquery.cuishifeng.cn/
11 .JQ function
    1) Control page style
    2) Access and operate DOM
    3) Event processing
    4) Provide a large number of plug-ins
    5) Ajax technology packaging
    6) Provide a large number of animation processing
    ...
12. Use JQ
    1) Local import
        < script src="./js/jquery-3.3.1.min.js"></script>
    2) CDN import
        <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5. 0/jquery.js"></script>

    Note: JQ must be introduced before its API can be adjusted. It can be introduced in the head tag, or it can be introduced at the end, usually at the end.
13. Selector
    1) Basic selector
        id: #id
        class: .class
        element: element
        * Select all tags (do not use it during project development, because it has to match all tags, and the performance is poor)
        , select multiple DOM
    2 ) Hierarchical Selector Selector
        1 Selector 2: Select all descendant elements of Selector 1 (Selector 2)
        Selector 1 > Selector 2: Select only child elements of Selector 1
        Selector 1+Selector 2: Select The first adjacent element (sibling element) next to selector 1
        selector 1 ~ selector 2: Select all sibling elements of selector 1
    3) Filter selector
        a. Simple filter selector
            : first or first() The first element
            : last or last() The last element
            : not (selector) Elements other than selector
            : even Even elements
            : odd Odd elements
            : eq (index) The nth element
            :gt(index) is greater than the nth element
            : lt(index) is less than the nth element
            : header Select all header elements h1-h6
        b. Content filter selector
            : contains(text) Get the content containing the specified text Element
            : empty Get elements that do not contain sub-elements or text content
            : has(selector) Get elements that match the selector
            : parent Get elements that contain sub-elements or text
        c. Visibility filter selector
            : hidden Select display: none or Elements of hidden text fields (hidden)
            : visible Select elements of display: block
        d. Attribute filter selector
            [attr] Get elements with specified attributes
            [attr=value] Get elements whose attribute value is value
            [attr!=value] Get Element whose attribute value is not value
            [attr^=value] Get the element whose attribute value starts with value
            [attr$=value] Get the element whose attribute value ends with value
            [attr*=value] Get the element whose attribute value contains value
            [attr1][attr2][attr3] Get the element with specified multiple attributes
    4) Form selector
        : input
        :button
        :submit
        :text
        :password
14. DOM operation
    1 ) Attribute operation
        a. Get attribute value
            attr (attribute name)
        b. Set attribute
            attr (attribute name, attribute value)
        c. Delete attribute
            removeAttr (attribute name)
    2) Text content operation
        a. Get text and form component content
            html() Labels can be manipulated
            text() can only manipulate text content, and labels that cannot be manipulated
            val() can only be used for form components
        b. Set (modify) text and form component content
            html(content)
            text(content)
            val(content)
        c. Delete text and form component content
            html('')
            text('')
            val('')
    3) Element style operation
        a. Set style
            css('attribute name','attribute value') set one Style
            css({'attribute name 1':'attribute value 1','attribute name 2':'attribute value 2',...}) set multiple styles b. operation class i) add class addClass(
        '
            class
                name ') to add a class name
                or:
                addClass('class name1 class name2....') Add multiple class names
            ii) Delete class
                removeClass() to clear the class name
                or:
                removeClass('class name') to clear the specified class name
                or:
                    removeClass('class name 1 class name 2....') to clear the specified Multiple class names
    4) Page element operations
        a. Create DOM node
            $(dom node content)
        b. Add DOM node inside
            append() Add DOM appendTo() at the end of the inside Add DOM to the last             prepend()
            of the inside Add DOM             prependTo() at the front of the inside Add DOM to the front of the interior         c. Add DOM nodes outside             before() Add before the current DOM (add at the same level)             insertBefore() Add the DOM before the current element (add at the same level)             after() After the current DOM Add (add at the same level)             insertAfter() Add DOM to the current element after (add at the same level)         d. Copy the DOM node             clone() Only copy the DOM element             clone(true) Copy the DOM and the events bound to it         e. Delete DOM node             remove() deletes the current DOM and child elements












            remove(dom node) Delete the specified DOM in the same level DOM
            empty() Delete the child elements under the current DOM, keep the current DOM

Guess you like

Origin blog.csdn.net/qq_39953312/article/details/116334472