JavaScript basics and functions, BOM, DOM nodes and DOM node operations

Three ways to use js
 
1. Directly in the HTML tag, use the event attribute to call the js code:
<button onclick="alert('Click me')">Click me! <tton>

2. Use script tags anywhere on the page

<script type="text/javascript">
  alert('哈哈哈')
</script>

3. External: Use the src attribute of the script tag to select the external address, and the type attribute to select "text/javascript" charset="utf-8"

<script src="js/01-js.js" type="text/javascript" charset="utf-8">
</script>

Precautions:

1. js code can be used anywhere on the page, but the different placement will affect the execution order.
2. The introduced external script tag can no longer contain any js code.
 
 
variables in js
 
1. Variable declaration:
var num1=1; //The variable declared with var is a local variable and is available within the function
num2="Hahahaha"; //The direct declaration is a global variable. Available globally.
var a=1,b,c=2; //Use one line of code to declare multiple statements, where b is undefined;
 
Notes on declaring variables in js
1. The keyword var for declaring variables in js, the type depends on the assignment type, and the default value is undefined;
2. The same variable in js can be modified in multiple assignments.
3. Variables can be declared using var, or they can be declared by direct assignment; var declarations are local variables; direct declarations are global variables.
4. The variables in js can have the same name, which is equivalent to covering the previous ones.
 5. Variable names are case-sensitive. Different case is not the same variable.
 
(6) data types in js:
null: empty, indicating an empty reference;
Undefined: declared with var, but assigned variable;
Number: numeric type, including integer and floating point;
Boolean: true or false;
String:string;
Object: Object.
There are no characters in js, both single and double quotes are strings.
 
Common Numeric Functions
①isNaN is used to detect whether a variable is not a number (Not a Number)
When checking, the Number function will be called first, trying to convert the variable to a numeric type. If the final result can be converted to a numeric value, it will not be NaN.
 
②Number is used to convert various data types into numeric types
  >>> Undefined cannot be converted to return NaN
  >>> null turns to 0
  >>> Boolean true to 1 false to 0
  >>> String can be converted if the string is a pure numeric string
Cannot convert returns NaN if string contains non-numeric characters 
If it is an empty string, turn it to 0, which can be a space
 
③parseInt converts a string to a numeric type
  >>>If it is an empty string, it cannot be converted to ""-->NaN
  >>>If it is a pure numeric type string, it can be converted and the decimal point is directly rounded off, "123.9"-->123 "123"-->123
  >>> If it contains non-numeric characters, convert the integer before the non-numeric value "123a"-->123 "a123"-->NaN
 
④parseFloat The conversion mechanism is the same as parseInt, the difference is that when converting a numeric string, if the string is a decimal, the decimal point can be retained
    "123.9"-->123.9   "123"-->123
 
⑤typeof detects the data type of a variable
    String -->string Value -->number true/false-->boolean Undefined -->Undefined Object/null-->Object Function -->function
 
 
Common input and output
alert() popup output
prompt(); pop-up window input Accept two parameters, ① input prompt content ② default text of the default box (both parts can be omitted) The input content is a string by default
document.write("<h1>12345</h1> <h5></h5>") prints on browser screen
console.log("2222") browser console print
 
Operators in JS
①Division sign No matter whether both sides of the symbol are integers or decimals, the decimals will be retained according to the actual result after the sign
② === requires the data on both sides of the equation, the type and value must be the same, if the type is different, return false directly
③== only judges the data on both sides, and does not care whether the data types on both sides are the same
④!== not all equal != not equal
⑤Conditional operator a>b?true:false
 
In JS, only bitwise operations can be performed. If both sides are not data types, they will be converted to numeric types during the operation.
&& perform logical operations
 
True and false judgment in js
 
1.Boolean true is true false is false
2. Numerical type 0 is false, non-0 is true
3. String type "" is false, non-empty string is true
4.null/Undefined/NaN are all false
5.object is all true
 
Various data types can be placed in the () of the switch structure
When comparing, use === to determine the type and value must be the same
 
 
Function declaration and call in js
 
function declaration format
function function name (parameter 1, parameter 2...){
     // function body code 
    return return value;
}

 

 
1. Function call
①Direct call function name (parameter 1, parameter 2...);
 
②Invoke via event In HTML tag, invoke via event attribute
<button onclick="focus('123','345')">点</button>

 

 
2. Notes on function declaration and invocation
 
①Whether there is a return value in the function, it only depends on whether there is a return in the function. No need to declare it deliberately. In JS, there is a return value that can not be received, or no return value can be received, the result is Undefined
 
②The formal parameter list of a function in JS has nothing to do with the actual parameter list. That is to say, there are parameters that can be unassigned (undefined), and no parameters can be assigned. The actual number of parameters of the function depends on the actual parameter list.
 
③ In JS, the function is the only scope of the variable, then, the formal parameter of the function is the local variable belonging to the function
 
④There is no distinction between function declaration and calling statement, that is, you can write the calling statement first, and then declare the function func(); function func() {}
 
Declaration and use of anonymous functions
1. Anonymous function expression var func=function(){} calls function func();
Note that the function call statement must be placed after the declaration statement
 
2. Assign an anonymous function directly to an event
      window.onload=function () { } //Document ready function, ensure that the code in the function is executed after the HTML document is loaded
      document.getElementById("btn2").onclick=function () { }
           
3. Self-executing function
①!function(){ }(); Use ! at the beginning to indicate that this is a self-executing function
 
②(function(){}()); Wrap anonymous function declaration and call with ()
 
③(function(){})(); Use () to wrap the anonymous function declaration statement;
 
Execution order of JS code
The execution of JS code is divided into two stages: Check the compilation stage Code execution stage
 
Check the compilation phase, mainly check syntax errors, variable declarations, function declarations and other declaration operations
  Action performed var num; function func1() {} var func2;
Code execution stage Variable assignment, function call and other execution statements belong to the code execution stage
Operation performed console.log(num); num=1; func1(); func2(); func2=function () {};
 
console.log(num);
var num=1 ;
func1();  
function func1() {}
func2();  
var func2=function () {}

 

arguments object
1. Action is used to save all the arguments of the function
  >>> But when the function has actual parameters, you can use the array subscript to access all the actual parameters of the function
  >>>alert(arguments[4])
2. The number of elements in arguments depends on the actual parameter list and has nothing to do with the number of formal parameters
 
3. Once the actual parameter is passed in when the function is called, the formal parameter corresponding to the number of digits will be bound to the element corresponding to the arguments
  Modify the formal parameters, the corresponding elements in the arguments will be changed, and vice versa
  However, if no actual parameters are passed in the first position, the formal parameters and arguments of this position will not be associated
 
4.arguments.callee(); executes a reference to the current function, which is used to call itself recursively in the function
 
WELL
 
screen object
console.log(window.screen);
console.log(screen);
console.log(screen.width);
console.log(screen.height);
console.log(screen.availWidth); // Available width 
console.log(screen.availHeight); // Available height=screen.height-bottom taskbar height

 

location object
console.log(location);
console.log(location.href); // complete URL path 
console.log(location.protocol);         // protocol name 
console.log(location.hostname);      // hostname 
console.log(location.port); // port number 
console.log(location.host); // host name + port number 
console.log(location.pathname);      // file path 
console.log(location.search); // parameter part starting with ? 
console.log(location.hash); // Anchor location starting from #

 

 
Use location for page jump
function gotobaidu () {
     ①   location="http://www.baidu.com";
     ②   window.location.href="http://www.baidu.com";
}

 

Jump to the page, after loading the new interface, you can click the back button to return
function gotobaiduByAssign ()
location.assign("http://www.baidu.com"); }

 

Jump to the page, there is no back button after loading the new interface, you cannot go back
function gotobaiduByReplace(){
location.replace("http://www.baidu.com"); }

 

refresh the current page
location.reload(); Refresh the page if there is a local cache, it will be read from the cache, which is equivalent to pressing F5
location.reload( true ); Force refresh, regardless of whether there is a cache, it will request the background to load the latest data, equivalent to Ctrl+F5

 

 
history object
console.log(history);
console.log(history.length); // Used to record the number of historical pages that the current page jumps to

 

 
Clicking to go to the previous page is equivalent to the browser's forward button
function forward(){
history.forward(); }

 

Clicking to go to the next page is equivalent to the browser's back button
function back(){
history.back(); }

 

Indicates jumping to any interface in the browsing history
+1 means the previous page -1 means the next page 0 means the current page so history.go(0); is equivalent to refreshing the page
function go(){
history.go(); }

 

 
navigator object
Returns various system information about the browser
console.log(navigator);
 
Output all plugins for the browser 
for (var i=0;i<navigator.plugins.length;i++) {
console.log(navigator.plugins[i].name); }
 

 

Common methods of window object
①prompt() pop-up input
②alert() pop-up output
 
③confirm() The prompt box to be confirmed to delete returns true and false respectively
 
④close() closes the current browser window
 
⑤open() Opens a new window parameter 1 address of the new window Parameter 2 The name of the new window is useless Parameter 3 The various configuration properties of the new window scrollbars=yes indicates whether to display the scroll bar only useful in IE
window.open("http://www.baidu.com","百度","width=600px, height=600px,top=100px,left=100px,scrollbars=yes");
 
 
⑥setTimeout delayer, indicating how many ms delay to execute a function
  Parameter one can be passed to an anonymous function or a function name
  Parameter two delay milliseconds
  Parameter three to parameter n parameters passed to the callback function
  setTimeout(function(num1,num2){},2000,"Hahaha",123,456,47)
 
⑦setInterval timer indicates how many ms to execute the function once
  Other usage is exactly the same as setTimeout
 
⑧clearInterval clear timer
⑨clearTimeout Clear the delayer
  When declaring the timer, you can accept the returned id and return the id to clearInterval to clear
 
 
DOM number of nodes
 
DOM nodes are divided into three categories: element nodes (label nodes), attribute nodes, text nodes
Attribute nodes and text nodes belong to the child nodes of the element node, so when operating, you need to select the element node first, and then modify the attributes and text.
 
View element nodes
1. Use the getElement series method
var  li=document.getElementById("first")
var  list1=document.getElementsByClassName("cls")
var  list2=document.getElementsByName("name")
var  list3=document.getElementsByTagName("li")

 

Precautions
①id cannot have the same name. If the id is repeated, only the first one can be taken
 
②When getting the element node, you must wait until the DOM tree is loaded before you can get the two ways: write js at the end of the document and write the code into the window.onload function
 
③ The data obtained through the getElements series is in array format, and each element must be obtained during the operation before the operation can be performed, but the array cannot be operated directly.
  document.getElementsByClassName("cls").click()=function(){};  错误
  document.getElementsByClassName("cls")[0].click()=function(){}; 正确
 
④ In this series of methods, you can also select a DOM node first, and select the desired node from the selected DOM nodes.
  document.getElementById("first").getElementsByTagName("li");
 
2. Through the querySelector series method
 
①Pass in a selector name and return the first element found, usually used to find the id var dq1=document.querySelector("#id")
 
②Pass in a selector name, and return all the elements found, no matter how many are found, return the array format var dqs1= document.querySelectorAll("#div1 li")
 
View Modify Attribute Node
 
View attribute node .getAttribute("Attribute name")
 
Set attribute node .setAttribute("attribute name", "attribute value")
 
Matters needing attention .setAttribute() has compatibility problems in old versions of IE, you can use the . symbol instead
      document.getElementById("first").classname="haha";

 

 
 
 
Multiple ways to modify css in JS
 
1. Use setAttribute to set class and style
document.getElementById("first").setAttribute("class","class1")
document.getElementById("first").setAttribute("style","color:red")

 

 
2. Add a class selector using .className
document.getElementById("first").className="class1"

 

 
3. Use .style. style name to directly modify a single style, note that style names must use camel case naming
document.getElementById("first").style.color="red";
document.getElementById("first").style.fontSize="18px";

 

 
4. Use .style or .style.cssText to add a line-level style
 
  document.getElementById("first").style="color:red";   //IE不兼容
  document.getElementById("first").style.cssText="color:red";

 

 
View Settings Text Node
 
.innerHTML gets or sets the HTML code in a node
document.getElementById("first").innerHTML
document.getElementById("first").innerHTML="<a href=''>hah</a>"

 

 
 
.innerText gets or sets the text in a node, cannot set HTML code
document.getElementById("first").innerText

 

 
Hierarchical Node Operations
1. .childNodes gets all child nodes of the current node including element nodes and text nodes
    .children Gets all element child nodes of the current node, excluding text nodes
   
2. .parentNode gets the parent node of the current node
   
3. .firstChild gets the first child node including text nodes such as carriage return
  .firstElementChild Get the first element node without text nodes
 
  .lastChild .lastElementChild get the last
 
4. .previousSibling gets the previous sibling node of the current node, including text nodes
  .previousElementSibling Get the previous element sibling node of the current node
 
    .nextSibling .nextElementSibling get the next one
 
5. .attributes gets all attribute nodes of the current node and returns an array format
 
Create and add nodes
 
1. .document.createElement("tag name") creates a new node and returns the created new node. You need to set attributes for the new node with .setAttribute
 
2. Parent node.insertBefore(new node, target node) Insert the new node in the parent node before the target node Parent node.appendChild(new node) Inside the parent node Finally, insert a new node
 
3. Source node.cloneNode() Clone a node. Passing in true means to clone the source node and all child nodes of the source node. Passing in false or no pass means that only the current node is cloned, not the child nodes.
 
 
 
delete replacement node
 
1. Parent node.removeChild(child node) From the parent node, delete the specified child node
 
2. Parent node.replaceChild(new node, old node) Replace the old node with the new node in the parent node
 
 
 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325127354&siteId=291194637