Python phase 3 learning day04

1, JavaScript Foundation

1, JavaScript overview

1. What is JavaScript

1) JS introduction

JS, for short, is a browser interpreted language, which is nested in HTML files and handed to the browser for interpretation and execution. It is mainly used to realize the dynamic effect of web pages, user interaction, front and back-end data transmission, etc.

2) JS composition

  1. The core syntax ECMAScript standardizes the basic syntax of JS
  2. Browser Object Model - BOM
    Browser Object Model provides a series of methods to operate the browser
  3. Document Object Model DOM
    Document Object Model, which provides a series of methods to manipulate documents

2. Usage

  1. Element binding event
    • Event: refers to the user's behavior (click, double click, etc.) or the state of the element (focus state of the input box, etc.)
    • Event handling: the element listens to an event and automatically executes the event handling function after the event occurs.
    • Common events: onclick
    • Syntax: bind the event name to the element in the form of label attribute, and customize event handling.
    <!--Click the button to output on the console-->
    <button onclick="console.log('Hello World');">click</button>
    
  2. Document inline. You can use either embedded JS code or imported external JS files, but you can only choose one from the other.

2, Basic grammar

1. Syntax specification

  1. JS is composed of statements, which are composed of keywords, variables, constants, operators and methods The semicolon can be used as a sign of the end of the statement or omitted
  2. JS is strictly case sensitive
  3. Annotation syntax
    Single line note usage//
    Multiline comment use / **/

2. JS variables and constants

1) Variable

  1. Function: used to store data that can be dynamically modified during program operation
  2. Syntax: use key var declaration to customize variable name
    var a;		//Variable declaration
    a = 100;	//Variable assignment
    var b = 200; //Declaration and assignment
    var m,n,k;	//Declare multiple variables at the same time
    var j = 10,c = 20; //Multiple variables are declared and assigned at the same time
    
  3. Naming conventions:
    • Variable name, constant name, function name and method name are user-defined. They can be composed of numbers, letters, underscores and $. It is forbidden to start with numbers
    • Var const function if else for while do break case switch return class
    • Variable names are strictly case sensitive
    • The variable name shall be known by name as much as possible, and multiple words shall be composed of a small hump, such as "userName"
  4. Usage Note:
    • If the var keyword is omitted and the variable is not assigned a value, an error will be reported for direct access
    • The variable is declared with the var keyword but not assigned a value. The initial value of the variable is undefined
    • The variable omits the var keyword declaration, has been assigned, and can be used normally Influence variable scope

2) Constant

  1. Function: store data that cannot be modified once defined
  2. Syntax: must be declared and assigned at the same time
    const PI = 3.14;
    
  3. be careful:
    • Once a constant is defined, it cannot be modified. Forced modification will report an error
    • The naming standard is the same as that of variables. In order to distinguish variables, the constant name adopts all uppercase letters

3. Data type

1) Basic data type

  1. number numeric type

    • integer
      1. Decimal representation
      ```javascript
       var a = 100;
      ```
      2. Octal representation
         Prefix with 0
      ```javascript
       var b = 021; //The result is decimal 17
      ```
      3. hexadecimal
         With 0 x Prefix
      ```javascript
       var c = 0x35;//The result is 53 decimal
      ```
         use : Integers can be expressed in different hexadecimals,When outputting from the console, it will always be output in decimal system
      
    • decimal
      1. Decimal point representation
       var m = 1.2345;
      
      1. Scientific counting method
        Example: 1.5e3
        E indicates that 10 is the bottom, and the value after e indicates the power of 10
        1.5e3 is equivalent to 1.5 * 10 (3)
  2. String string type
    String: it is composed of one or more characters. It is represented by "" or '. Each character has corresponding Unicode encoding

    var s = "100";
    var s1 = "Zhang San";
    
  3. Boolean boolean type
    Only true and false values, Boolean and number values can be converted to each other. True is 1 and false is 0

    var isSave = true;
    var isChecked = false;
    
  4. undefined (the value returned by the program)
    Special value. undefined is displayed when the variable declaration is not assigned

    var a;
    console.log(a);//undefined
    
  5. Null null type (actively used)
    null is used when dereferencing an object, indicating that the object is empty

2) Reference data type

It mainly refers to objects and functions

4. Data type conversion

When different types of data participate in the operation, they need to be converted

1) Cast type

  1. Convert string type
    Method: toString()
    Returns the converted string
var a = 100;
a = a.toString(); //"100"
var b = true;
b = b.toString(); //"true"
  1. Convert number type

    • Number(param)
      The parameter is the variable or value to be converted to data type, and the converted result is returned:
      If the conversion is successful, the number value is returned
      If the conversion fails, NaN (not a number) is returned. As long as there are non number characters in the data, the conversion fails and NaN is returned
        Number("abc")
        typeof NaN
        Number(undefined)
        Number(null)
    
    • parseInt(param)
      The parameter is the data to be parsed
      Function: parse integer values from data
      Process:
      1. If the parameter is of non string type, it will be automatically converted to string
      2. Turn number for each character from left to right. If the conversion fails, stop backward parsing and return the result
    • parseFloat(param)
      Function: extract the number value, including integer and decimal parts

2) Implicit type conversion (automatic conversion)

  1. When the "+" operation is performed between the string and other data types, it indicates the splicing of the string, which is no longer a mathematical operation
    Conversion rules: convert non string data into strings and splice them. The final result is a string

  2. In other cases, the operand is converted to number for mathematical operation

5. Operator

1) Assignment operator

= Assign the value on the right to the variable on the left

2) Arithmetic operator

+ - * / %  Addition, subtraction, multiplication and division

3) Compound operator

+= -= *= /= %=

4) Self increasing or self decreasing operator

++ -- The self increment and self decrement of variables refer to the process on its own basis +1 or-1 Operation of

be careful:

  • When self increasing or self decreasing operators are combined with variables alone, there is no difference between before and after placement
  • If the self increasing or self decreasing operator is used in combination with other operators, to distinguish between prefix and suffix, make prefix, first + + / –, and then perform assignment or other operations. If making suffix, first combine other operators, and then + + / –

5) Relational operator / comparison operator

> <     
>= <=
==(equal) !=(Unequal)
===(Congruent) !==(Incomplete equivalence)
  1. Relational operators are used to judge the relationship between expressions. The result is always Boolean true/false

  2. use

    • Comparison between strings
      Compare the Unicode code of each character in turn. As long as a character compares the result, the final result is returned
    • Other situations
      All operands are converted to number for numerical comparison. If an operand cannot be converted to number, it becomes NaN to participate in the comparison operation, and the result is always false

    null and other data types do equivalent comparison operations and are not converted to numbers
    Null and undefined are equal, but null and undefined are not equal

  3. Equality and congruence

    • Equal: do not consider the data type, but only compare the values (including automatic type conversion)
    • Congruence: data type conversion will not be performed. Congruence is judged only when the data types are consistent and the values are equal

6) Logical operator

  1. &&Logic and conditions1 & & condition2
    The final result is true only when the expressions are valid at the same time;
  2. ||Logic or condition 1 | condition 2
    As long as one of the expressions is true, the final result is true;
  3. ! Logical non! condition
    Negate the result of an existing expression

7) Ternary operator

Syntax:

Expression 1 ? Expression 2 : Expression 3;

Process:
Judge whether expression 1 is true and return Boolean value
If expression 1 holds, execute expression 2;
If expression 1 does not hold, execute expression 3;

3, Process control

1. Function

Control the execution order of the code

2. Classification

1) Sequential structure

Execute code statements from top to bottom

2) Branch / select structure

1. if statement
  • Simple if structure
    if(Conditional expression){
    	Code snippet executed when the expression is valid
    }
    
    Note: all values except zero are true, and the following conditions are false and false
    if(0){}
    if(0.0){}
    if(""){} //Empty string
    if(undefined){}
    if(NaN){}
    if(null){}
    
    Special writing:
    {} can be omitted. Once omitted, the if statement only controls the first line of code after it
  • if - else structure
    if(Conditional expression){
    //Execute when conditions are met
    }else{
    //Select execute when the condition is not true
    }
    
  • Multiple branch structure
      if(Condition 1){
      	//Execute when condition 1 is true
      }else if(Condition 2){
      	//Execute when condition 2 is true
      }else if(Condition 3){
      	//Execute when condition 3 is true
      }...else{
      	//Execute when conditions are not satisfied
      }
    

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-sCNLSyl5-1625355086079)(assets\if.png)]

2. switch statement
  • Syntax:
switch(value){
	 case Value 1 :
	 //Code snippet executed when value matches congruent with value 1
	 break; //End match
	 case Value 2 :
	 //Code snippet executed when value matches congruent with value 2
	 break;
	 case Value 3 :
     //Code snippet executed when value matches congruent with value 3
	 break;
	 default:
 	 //Statements executed by default after all case matching fails
 	 break;
}
  • use:
1. switch Statement for value matching, case Used to list all possible values; only switch()The value of the expression is the same as case Is executed when the value of matches congruence case Corresponding code segment
2. break It is used to end matching and no longer execute backward; Can be omitted, break Once omitted, it will be matched from the current case At the beginning, execute all code statements backward until the end or encounter break Jump out
3. default Used to represent all case In case of matching failure, it is generally written at the end to do the default operation
4. Multiple case Shared code snippet
  		case Value 1:
  		case Value 2:
  		case Value 3:
  		//Any of the above values matches the code snippet that will be executed by congruence

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-3as4hhhth-1625355086085) (assets \ switch. PNG)]

3) Cyclic structure

  • effect
    Execute a piece of code repeatedly according to the conditions
  • classification
  1. while Loop
Define loop variables;
   while(Cycle condition){
   Code snippet to execute when conditions are met
   Update loop variable;
}
  1. do-while Loop
do{
	Circulatory body;
	Update loop variable
}while(Cycle condition);

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-yyenw hiw-1625355086088) (assets \ while. PNG)]

Difference from while loop:

  • The while loop judges the loop condition first, and executes the loop body only when the condition is established
  • The do while loop executes the loop body once regardless of whether the condition is true or not
  1. for loop
for(Define loop variables;Cycle condition;Update loop variable){
	Circulatory body;
}

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-LzrdP6dg-1625355086092)(assets\for.png)]

Cycle control:

  1. break force end loop
  2. continue ends the current cycle and starts the next cycle
    Loop nesting:
    Add another loop nested within the loop

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-rT8lrVLb-1625355086096)(assets\break.png)]

4, Functions

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-g1mq1ILq-1625355086100)(assets/fn0.png)]

1. Function

Encapsulate a piece of code to be executed

2. Grammar

  //Function declaration
  function Function name(parameter list){
  	Function body
  	return Return value;
  }
  //function call
  Function name(parameter list);

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-eQ6jsX1a-1625355086101)(assets/fn2.png)]

3. Use

The function name is customized. See the meaning of the name. The naming specification refers to the naming specification of variables. Normal functions start with lowercase letters and are used to distinguish constructors(Constructors start with uppercase letters and define classes)

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-WdQLthyp-1625355086102)(assets/fn3.png)]

4. Anonymous function

Anonymous function: a function that omits the function name. The syntax is:

  • Anonymous function self execution
 (function (Formal parameter){
  
 })(Argument);
  • Define variables to receive anonymous functions
 var fn = function (){};
 fn(); //function call

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-hZrlOwml-1625355086103)(assets/fn1.png)]

5. Scope

In JavaScript, the scope is divided into global scope and function scope. The {} of the function is used as the basis for dividing the scope

  1. Global variables and global functions
    • As long as the variables defined by var keyword outside the function, or the functions are global variables and global functions, they can be accessed anywhere
    • All variables that omit the var keyword definition are global variables
  2. Local variable / local function
    • The variables defined with the var keyword inside the function are local variables, and the functions defined inside the function are also local functions, which can only be used in the current scope and cannot be accessed by the outside world
  3. Scope chain
    To access variables or functions in a local scope, first search from the current scope. If there is no variable or function in the current scope, search from the parent scope to the global scope

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-P106nJ5O-1625355086104)(assets/scope.png)]

5, DOM node operation

The full name of DOM is "Document Object Model", which provides methods for operating HTML documents. (Note: each HTML file is regarded as a document in the browser. Operating a document is actually operating page elements.)

1. Node object

JavaScript encapsulates elements, attributes, text and even comments in html documents, called node objects, and provides related attributes and methods.

2. Access node

  • Element node (operation label)
  • Attribute node (action label attribute)
  • Text node (text content of operation label)

Label attributes are attributes of element node objects, which can be accessed using point syntax, for example:

h1.id = "d1"; 		 //set method
console.log(h1.id);  //get method
h1.id = null;		//remove method

be careful:

  • Property values are represented as strings
  • The class attribute needs to be renamed className to avoid conflicts with keywords, for example:
    h1.className = "c1 c2 c3";

3. Get multiple DOM elements and control attributes

  1. Get the element node list according to the tag name
var elems = document.getElementsByTagName("");
/*
Parameters: tag names
 Return value: node list. You need to obtain the specific element node object from the node list and add the corresponding subscript.
*/
  1. Get the element node list according to the class attribute value
var elems = document.getElementsByClassName("");
/*
Parameter: class name (class attribute value)
Return value: node list
*/
  1. The element node object provides the following attributes to manipulate the element content
innerHTML : Read or set element text content,Recognizable tag syntax
innerText : Set element text content,Unrecognized label syntax
value : Reads or sets the value of the form control
  1. Operate on attribute values in the DOM tree:
elem.getAttribute("attrname");//Returns the corresponding property value according to the specified property name
elem.setAttribute("attrname","value");//Add attributes to the element, and the parameters are attribute name and attribute value
elem.removeAttribute("attrname");//Remove specified attribute
  1. Action element style:
    Add id and class attributes to the element, or operate the inline style of the element, access the style attribute of the element node, and obtain the style object; The style object contains CSS properties and uses point syntax operations.
p.style = "width:300px;";
p.style.color = "white";
p.style.fontSize = "20px";

be careful:

  • The attribute value is given as a string, and the unit cannot be omitted
  • If the css attribute name contains a connector, when using JS to access, the connector will be removed and changed to hump, font size - > fontsize

2, jQuery

1. Introduction

jQuery is a tool library of JavaScript. It encapsulates DOM operation, event processing, including data processing and Ajax technology in native JavaScript, providing a more perfect and convenient method.

2. Use

1) Introduce

jquery syntax can only be used after introducing jquery files

  1. CDN network (standby)
  2. Local files (common)

2) Factory function - $()

The "$()" function is used to obtain element nodes, create element nodes, or convert native JavaScript objects into jQuery objects, and return jQuery objects. jQuery object is actually a class array object, which contains a series of methods of jQuery operation.
For example:

 //$() to get the element node, you need to pass in the selector of the string
 $("h1")
 $("#d1")
 $(".c1")
 $("body,h1,p")
 //The characteristics of the selector are consistent with the style selector

3) Native JavaScript objects and jQuery objects

The properties and methods of native JavaScript objects and jQuery objects cannot be mixed. You can convert each other as needed:

  1. Converting jQuery objects from native JavaScript
    $(native object), return jQuery object
  2. Converting jQuery objects to native JavaScript objects
    • Method 1: take the element according to the subscript and take it out as the native object
      var div = $("div")[0];
    • Method 2: use jQuery's get(index) to get the native object
      var div2 = $("div").get(0);

4) jQuery get element

jQuery gets elements through selectors, $("selectors")
Selector classification:

  1. Base selector
Label selector: $("div")
ID Selector: $("#d1")
Class selector: $(".c1")
Group selector: $("body,p,h1")
  1. Level selector
Descendant selector: $("div .c1")
Descendant selector: $("div>span")
  1. Filter selector, which needs to be used in combination with other selectors.
:first
  Match first element instance:$("p:first")
:last
  Match last element instance:$("p:last")
:odd
  Match elements corresponding to odd Subscripts
:even
  Match elements corresponding to even Subscripts
:eq(index)
  Matches the element of the specified subscript
:lt(index)
  Match subscript less than index Element of
:gt(index)
  Match subscript greater than index Element of
:not(selector)
  Negative screening,except()Outside the middle selector,Other elements

5) Operation element content

html() //Set or read the tag content, which is equivalent to the native innerHTML and can recognize the tag syntax
text() //Set or read the label content, which is equivalent to innerText. The label cannot be recognized
val()  //Set or read the value of the form element, which is equivalent to the native value attribute

6) Action label properties

  1. attr("attrName","value")
    Set or read label properties
  2. prop("attrName","value")
    Set or read label properties
    Note: there is basically no difference between attr() and prop() when setting or reading element attributes; However, when reading or setting the selected state of a form element (button), you must use the prop() method. attr() will not listen to the change of the selected state of the button, but only depends on whether the tag attribute checked is written
  3. removeAttr("attrName")
    Remove specified attribute

7) Action label style

  1. Add the id/class attribute to the element, corresponding to the selector style
  2. For class selectors, provide methods to manipulate class attribute values
addClass("className")	//Adds the specified class name
removeClass("className")//Remove the specified type. If the parameter is omitted, it means that the class attribute value is cleared
toggleClass("className")//Combined with user behavior, dynamically switch class names If the specified class name exists in the current element, it will be removed; Add if it does not exist
  1. Action inline style
css("Attribute name","Attribute value")  //Set inline style
css(JavaScriptON object)			 //Set a set of CSS Styles
/*
JavaScriptON Objects: common data transfer formats
 Syntax:
   {
    "width":"200px",
    "height":"200px",
    "color":"red"
   }
 */

8) Element creation, addition and deletion

  1. Create: use $("tag syntax") to return the created element
var div = $("<div></div>");	//Create element
div.html("Dynamic creation").attr("id","d1").css("color","red"); //Chain call to set content and properties
var h1 = $("<h1 id='d1'>Primary title</h1>");	//Set content, properties and styles while creating
  1. Add as child element
$obj.append(newObj);	//Add the child element newObj at the end of $obj
$obj.prepend(newObj);	//Add to $obj as the first child element
  1. Add as sibling element
$obj.after(newObj);		//Add sibling element after $obj
$obj.before(newObj);	//Add sibling element before $obj
  1. Removing Elements
$obj.remove();	//Remove $obj

9) Data and object traversal

  1. $(selector). The each () method specifies the function to run for each matching element

    $(selector).each(function(index,element){})
    

    Required. Specify the function to run for each matching element.

    • Index - index position of the selector
    • Element - current element
  2. The $. each() function is a tool class function provided by the framework. Through it, you can traverse the attribute values of objects and arrays and process them

    $.each(Object, function(index, data){});
    

    Required. Specify the function to run for each matching element.

    • Index - index position of the selector
    • Data - current data

10) jQuery event handling

  1. Document loading completed
    Native JavaScript method: window onload
    jQuery:
//Grammar one 
$(document).ready(function (){
  //Execute after the document is loaded
})
//Grammar II 
$().ready(function (){
  //Execute after the document is loaded
})
//Grammar III 
$(function(){
  //Execute after the document is loaded
})

difference:
The native onload event cannot be written repeatedly, which will cause coverage problems; jquery optimizes events. You can write the ready method repeatedly and execute it in turn

  1. Event binding method
    Omit the on prefix from the event name
  //on("event name", function)
  $("div").on("click",function(){});//The new version uses more
  //bind("event name", function)
  $("div").bind("click",function(){});//Version between 1.6-1.8
  //Event name as method name
  $("div").click(function(){});  
  1. This represents the trigger object of the event, which can be used in jquery. Pay attention to the conversion type. This is a native object. Only native properties and methods can be used. You can use $(this) to convert to jquery object and jquery method.

Timer method

Periodic timer
Function: execute the code at regular intervals

//Start timer:
var timerID = setInterval(function,interval);
/*
Parameters:
 function : For the code to be executed, you can pass in the function name; Or anonymous function
 interval : Time interval, in milliseconds by default, 1s = 1000ms
 Return value: returns the ID of the timer, which is used to turn off the timer
*/

Turn off timer:

//Turn off the timer corresponding to the specified id
clearInterval(timerID);

Disposable timer
Function: how long to wait before executing the code

//Turn on timeout call:
var timerId = setTimeout(function,timeout);
//Close timeout call:
clearTimeout(timerId);

Array array

1. Create

  var arr = [];

2. Features

  • The array is used to store several data, and each data is automatically assigned a subscript, starting from 0
  • The elements in the array are not limited to data types, and the length can be adjusted dynamically
  • Dynamic operation of array elements: read or modify array elements according to element subscripts, arr[index]

3. Properties and methods

  1. Attribute: length indicates the length of the array, readable and writable
  2. method:
    • push(data)
      Add one or more elements to the end of the array, separated by commas
      Returns the length of the array after adding

    • pop()
      Remove end element
      Returns the removed element

    • unshift(data)
      Add one or more elements to the head of the array
      Returns the length of the array after adding

    • shift()
      Removes the first element of the array
      Returns the removed element

    • splice(index,num)

      Add / remove items from array

      Returns the deleted item

    • toString()
      Convert array to string type
      Returns a string result

    • join(param)
      To convert an array into a string, you can specify the connector between elements. If the parameter is omitted, it is connected by comma by default
      Return string

    • reverse()
      Reverse array
      Return the rearranged array. Note that this method directly modifies the structure of the original array

    • sort()
      Sort the elements in the array in ascending Unicode encoding by default
      Return the rearranged array and modify the original array directly
      Parameter: optional, user-defined sorting algorithm
      Example:

      //Custom ascending order
      function sortASC(a,b){
        return a-b;
      }
      //Custom descending order
      function sortDESC(a,b){
      	return b-a;
      }
      //If the return value is > 0, exchange the values of elements, and b-a indicates descending order
      

      Function: when passed to sort() as a parameter, two elements will be automatically passed in for comparison. If A-B > 0, exchange the values of elements and customize the ascending arrangement

String object

1. Create

    var str = "100";

2. Features

The string uses an array structure to store each character, and automatically assigns subscripts to the characters, starting from 0

3. Properties

Length: gets the length of the string

4. Method

  • Convert letter case
    toUpperCase() to uppercase
    toLowerCase() to lowercase
    Returns the converted string without affecting the original string

  • Get character or character encoding
    charAt(index) gets the character of the specified subscript
    charCodeAt(index) gets the character encoding of the specified subscript
    The parameter is the specified subscript and can be omitted. The default value is 0

  • Gets the subscript of the specified character

    • indexOf(str,fromIndex)
      Function: get the subscript of the specified character, query from front to back, and return when found
      Parameters:
      str indicates the string to find, which is required
      fromIndex indicates the starting subscript, which is 0 by default
      return:
      Returns the subscript of the specified character. If the search fails, it returns - 1
  • Intercept string
    substring(startIndex,endIndex)
    Function: intercept strings according to the specified subscript range, startIndex ~ endIndex-1
    Parameters:
    startIndex indicates the starting subscript
    endIndex indicates the end subscript, which can be omitted. Omission indicates the end

  • substr(startIndex,len)

    Function: intercept the specified string according to the subscript

  • Split string
    split(param)
    Function: divide the string according to the specified characters and return the segmentation results in the form of array
    Parameter: Specifies the separator, which must be a character existing in the string. If it does not exist in the string, the segmentation fails and the array is still returned

Math object

1. Definitions

Math object mainly provides some methods of mathematical operations

2. Properties

  1. PI: math PI
  2. Natural logarithm: math E

3. Method

  1. Math.random(); Generate random numbers between 0-1
  2. Math.ceil(x); Round up x, ignore decimal places, integer bits + 1
  3. Math.floor(x); Round down x, discard decimal places, and retain integer digits
  4. Math.round(x); Round x to the nearest whole number

Date object

1. Create date object

  1. var date2 = new Date("2011/11/11");
  2. var date3 = new Date("2011/11/11 11:11:11");

2. Date object method

  1. Reads or sets the number of milliseconds of the current time: getTime()
  2. Get time component
    • getFullYear() gets the four digit year
    • getMonth() gets the month. The value range is 0 ~ 11
    • getDate() get date
    • getHours() get hours
    • getMinutes() get minutes
    • getSeconds() get seconds
  3. time difference
    • Date objects can be directly subtracted to obtain the time difference (milliseconds)
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>js Writing style</title>
  <script>
    console.log('stay head Medium js code');
  </script>
</head>
<body>
  <!-- Rest 11:11~11:25 -->
  <div onclick="console.log('hello world')">
    click me
  </div>

  <script>
    // js code
    console.log('stay body Lower js code');
  </script>
  <script src="demo.js"></script>

  <!-- <script src="demo.js">
    console.log('stay body Lower js code')
  </script> -->
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Variable constant</title>
</head>
<body>
  <script>
    // Before the js code is executed, the browser will find all variables declared with var in advance, advance the variable name to the top of the current scope, and then execute the js code line by line
    console.log(a,b,c,d);

    var a;
    console.log(a);//undefined
    a = 100;
    console.log(a);
    var b = 20;
    var c ,d = 30;
    console.log(c,d);

    // demo2.html:22 Uncaught ReferenceError: hello is not defined
    // console.log(hello);

    hello = 20;
    console.log(hello);

    const PI = 3.14;
    console.log(PI);
    console.log(PI*3);
    //Uncaught TypeError: Assignment to constant variable
    // PI = 3.1415926;


    var uname = 'qtx';
    var s = `hello ${uname}`;

    console.log(s);



    var upwd = null;
  </script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Data type conversion</title>
</head>
<body>
  <script>
    // To string
    var a = 10;
    console.log( a.toString() );
    console.log( a );
    console.log( typeof a );

    // console.log(String(null));

    //Uncaught TypeError: Cannot read property 'toString' of undefined
    // undefined.toString();

    // Uncaught TypeError: Cannot read property 'toString' of null
    // null.toString();


    // Transfer Number
    // '' --> 0
    // '123'  --> 123
    // '123abc'  -->  NaN
    // true  --> 1
    // undefined --> NaN
    // null --> 0


    console.log( parseInt('123abc') );//123
    console.log( parseInt(3.14) );//3
  </script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>operator</title>
</head>
<body>
  <script>
    // ++Self increasing -- self decreasing
    // A + + suffix + + a prefix a --- A
    var a = 10;
    // a = a+1;
    // a += 1;
    // When the self increment / self decrement operation is used alone, the difference in the writing of prefix and suffix is to make the value of variable + 1 / - 1
    // If Auto increment / Auto decrement operation is used to participate in other operations  
    // A + + will first return the result of a, and then let a+1
    // ++A will first let a+1 and then return the result of A
    ++a;
    console.log(a);//11
    console.log(a++ + a++ + a++);
    //          11     12    13
    console.log(a);//14

    // The comparison operation is automatically converted
    // === / !==  Automatic conversion will not occur
    
    // 16:01~16:15
    var age = prompt('Please enter age');
    // age>=18 || console. Log ('Access prohibited ');

    // age>=18? console.log('Access allowed '): console Log ('Access prohibited ')

    console.log(age>=18?'allow access to':'No access')
  </script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Branching structure</title>
</head>
<body>
  <script>
    // var age = prompt('Please enter age ');
    // if(age>=18){
    //   console.log('yes');
    // }else{
    //   console.log('no');
    // }
    // console.log('Program end ');
    
    // Get the score entered by the user and output the result according to the score
    // 90+   A
    // 80+   B
    // 70+   C
    // 60+   D
    // 60-   E


    // var score = prompt('Please enter score ');
    // if(score>=90){
    //   console.log('A')
    // }else if(score>=80){
    //   console.log('B')
    // }else if(score>=70){
    //   console.log('C')
    // }else if(score>=60){
    //   console.log('D')
    // }else{
    //   console.log('E')
    // }

    
    // Gets the month entered by the user and the number of days in the output month
    var m = prompt('Please enter the month');
    switch(m){
      case '1':
      case '3':
      case '5':
      case '7':
      case '8':
      case '10':
      case '12':
        console.log('31');
        break;
      case '2':
        console.log('28');
        break;
      case '4':
      case '6':
      case '9':
      case '11':
        console.log('30');
        break;

      default:
        console.log('Wrong month input!');
        break;
    }

    
    // if(m == 1){
    //   console.log('31')
    // }else if(m == 2){
    //   console.log('28')
    // }




  </script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Circular statement</title>
</head>
<body>
  <script>
    // var i = 0;
    // while(i<10){
    //   console.log(i++);
    //   // i += 1;
    // }
    
    for(var i = 0;i<10;i++){
      if(i%2){
        continue
      }
      console.log(i)
    }




    // console.log(0);
    // console.log(1);  

    // var i = 0;
    // while(i<10){
    //   console.log(i++);
    //   // i += 1;
    // }

    // Receive the password entered by the user. If the password is not 123456, let the user continue to enter until it is 123456
    // var upwd = prompt('Please enter password ');
    // while(upwd != '123456'){
    //   upwd = prompt('Please enter password ');
    // }

    // 17:05~17:20
    // do{
    //   var upwd = prompt('Please enter password ')
    // }while(upwd != '123456')

    // while(true){
    //   var upwd = prompt('Please enter password ');
    //   if(upwd == '123456'){
    //     break;
    //   }
    // }


  </script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>function</title>
</head>
<body>
  <button onclick="console.log('ok')"> 
    click me 
  </button>

  <script>
    // The function name declared by function will be advanced to the top of the current scope during precompiling. At this time, the function body code will also be advanced, and can be called anywhere in the current scope
    console.log( myMax(10,1000) );

    // function fn(uname){
    //   console.log('hello'+uname)
    // }
    // fn('Maria');

    function fn(a,b,c=10, ...args){
      console.log(a,b,c);
      console.log(args);
    }
    fn();//undefined undefined 10
    fn(10,20);//10 20 10
    fn(1,2,3);//1 2 3
    fn(1,true,3,4);//1 2 3

    function myMax(a,b){
      // if(a>b){
      //   console.log(a)
      // }else{
      //   console.log(b)
      // }
      return a>b?a:b;
    }
    console.log( myMax(10,20) );
  </script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <script>
    // 15:00~15:15
    // Gets the age entered by the user 
    // The age before ten years and the age after ten years are displayed respectively
    var age = Number( prompt('Please enter age') );
    // console.log(typeof age);//string
    // '20'+10 --> '20'+'10' -->'2010'
    // '20'-10 --> 20-10 -->10
    console.log(`Ten years ago:${age-10},Ten years later:${age+10}`);

    console.log(10+'');//'10'
    console.log('10'-0);//10
  </script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    #cart{
      width: 160px;
      height: 40px;
      border: 2px solid #999;
      background-color: #eee;
      /* Reference for child elements */
      position: relative;
    }
    #cart>div{
      color: #666;
      text-align: center;
      line-height: 40px;
    }
    #cart>span{
      color: #999;
      position: absolute;
      right: 10px;
      top: 0px;
      line-height: 40px;
    }
    /* 
      Absolute positioning to the upper right corner of the parent element adjusts the position on the right and above
      Fillet border sets the first three corners to 50% of the fillet and the last 0
      Red background white font font horizontal vertical center font do not tilt
    */
    /* 10:05~10:20 */
    #cart>i{
      position: absolute;
      top: -10px;
      right: 20px;
      background-color: #e4393c;
      color: #fff;
      width: 18px;
      height: 18px;
      text-align: center;
      line-height: 18px;
      font-style: normal;
      border-radius: 50% 50% 50% 0;
    }
  </style>
</head>
<body>
  <div id="cart">
    <div>My shopping cart</div>
    <span> &gt; </span>
    <i> 1 </i>
  </div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    .news{
      position: relative;
      width: 240px;
      height: 132px;
      /* border: 5px solid red; */
    }
    .news>div{
      position: absolute;
      bottom: 0;
      /* left: 0;
      right: 0; */
      color: #fff;
      background-color: rgba(255, 0, 0, 0.6);
      font-size: 14px;
      width: 100%;
      padding: 3px 0 3px 18px;
      /* Calculation method of box model 
      The default content box width and height attribute only indicates the size of the content box 
      Actual size = width / height + padding+border+margin

      The value of border box width and height attribute indicates that the content will be automatically adjusted when the and inner margin and border of all attributes, including the border, change
      Actual size = width / height + margin
      */
      /* box-sizing: content-box; */
      box-sizing: border-box;
    }
  </style>
</head>

<body>
  <div class="news">
    <img src="imgs/img02.png" alt="">
    <div>Samsung falls into the storm of closing the mobile phone factory again</div>
  </div>
</body>

</html>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <!-- 
    Box model
    Determines the actual size of the current page element in the page by default = width/height+padding+border  +margin
    Adjust distanceadjust the distance between the element content and the border. Use the inner margin
            Adjust the distance between the current element and other elements and use the outer margin

    Floating layout
        Sets the horizontal arrangement of block elements
        Breaking away from the default layout does not occupy a place in the page
        Solution 1.Sets the height of the parent element
                2.Add to parent element overflow:hidden;
                3.Add an empty block element at the end of the parent element to set the block element clear:both;

    Positioning layout
        position:relative/absolute/fixed
        
        top/right/bottom/left
    
   -->
</body>
</html>

Keywords: Python Javascript html

Added by KirstyBurgoine on Wed, 26 Jan 2022 15:15:47 +0200