JavaScript basics and functions, bom,dom node and DOM node operations

Source: Internet
Author: User
Tags script tag tag name

three ways to use JS1. Directly in the HTML tag, using the event properties, invoke the JS code:
<button onclick= "alert (' Point Me ')" > Point me! <tton>

2. From anywhere on the page, use the script tag

<script type= "Text/javascript" > alert (' ha ha ')</script>

3. External: Use the script tag src attribute to select an external address, type attribute 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 placed anywhere on the page, but the placement of different positions will affect the order in which it is executed. 2. The external script tag that is introduced can no longer contain any JS code.the variables in JS1. Declaration of variables: var num1=1; Variables declared with Var, are local variables, can be used within the function num2= "haha haha"; The direct declaration is a global variable. Globally available. var a=1,b,c=2; Declare multiple statements with a single line of code, where B is undefined; Note for variables declared in JS 1.js the keyword var of the variable declared, the type depends on the assignment type, and the same variable in the default value Undefined;2.js can be modified in multiple assignments in the data type. 3. Variables can be declared with Var, or they can be directly assigned; VAR is declared as a local variable; directly declared as a global variable. The variable in 4.js can have the same name, which is equivalent to the front of the cover. 5. Variable names are case-sensitive. The case is different from the same variable. JS (6 types) data type:Null: null, indicating an empty reference; Undefined: A variable declared with Var but assigned to a value; Number: Numeric type, containing integer and floating point types; Boolean: TRUE or false; String: An object: a literal. 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 non-numeric value (not a number) when the check calls the number function, attempting to convert the variable to a numeric type if the final result can be converted to a value, it is not nan ②number       for converting various data types to numeric types >>>  undefined cannot convert return nan >>>  null to 0 >>>  BOOLEAN&N Bsp True to 1  false to 0 >>>  string if the string is a pure numeric string, you can convert if the string contains non-numeric characters, you cannot convert the returned nan  if the empty string is converted to 0, which can be a space  ③parseint     Converts a string to a numeric type >>> if an empty string cannot go     ""-->nan >>> If it is a pure numeric type string, it can be converted and the decimal point is directly shed, not reserved      "123.9"-->123   "123"-->123 >>> If a non-numeric character is included, the integer preceding the non-numeric value is converted     "123a"-->123   "A123"-->nan ④parsefloat   The   conversion mechanism is the same as parseint, but when you convert a numeric string, you can leave the decimal point "123.9"-->123.9   "123" If the string is a decimal-->123 ⑤typeof    detecting a variable's data type string-->string   numeric-->number   true/false-->boolean  undefined-- >Undefined       Object/null-->object  function-->function   common input and outputAlert () Pop-up window output prompt (); Pop-up window input to the two parts of the parameters, ① input prompt content ② default text (both parts can be omitted) the input content is the default string document.write (" the operators in JS① division sign regardless of whether the symbol is an integer or a decimal, after the end will be retained according to the actual results of the decimal ②=== require data on both sides of the equation, the type and value must be the same, if the type is different, directly return false③== only judge the data on both sides, do not care whether the data type is the same ④!== ⑤ conditional operator A>b?true:false in JS, can only perform bitwise operations, if the two sides are not data types, will be converted to a number type in the arithmetic && logical operation the true and false judgment in JS1.Boolean true False for false 2. Value type 0 is false non 0 is true 3. String Type "" is false non-empty string true 4.null/undefined/nan all false 5.object full true Swit CH structure () can put various data types in comparison to the use of = = to determine the requirement type and value must be the sameThe declaration and invocation of functions in JSFormat of function declarations
function name (parameter 1, parameter 2 ...) {    // function Body Code    return return value;}

1. Function call ① Call Function name directly (parameter 1, parameter 2 ...); ② through an event call in an HTML tag, via an event property
<button onclick= "Focus (' 123 ', ' 345 ')" > Points </button>

2. Notice of function declaration and invocation There is no return value in the ① function, only depending on whether there is no return in the function in JS, there is a return value can not receive no return value can also be received, the result is the parameter list of the function in Undefined②js and the argument list has no association   In other words, parameters can be unassigned (unassigned undefined), and no parameters can be assigned.    The number of actual arguments for a function is dependent on the argument list ③js the function is the only scope of the variable then, the function's formal parameter is the function of the local variable ④ function declaration and the invocation of the statement does not have the point, that is, you can write the call statement, and then declare the function func (); function func () {} Declaration and use of anonymous functions1. anonymous function expression var func=function () {} Call function func (); Note that the function's invocation statement must be placed after the declaration statement 2. Assign an anonymous function directly to an event Window.onlo           The Ad=function () {}///document-ready function ensures that the code in the function executes document.getElementById ("BTN2") after the HTML document is loaded. Onclick=function () {}  3. Self-executing function ①!function () {} ();   Start with! Indicates that this is a self-executing function ② (functions () {} ());   Use () to wrap the anonymous function declaration with the Call ③ (function () {}) (); Use () to wrap an anonymous function declaration statement; the execution order of JS codeThe execution of the JS code is divided into two phases to check the compilation phase of the code execution phase to check the compilation phase of the key to check the syntax of the error variable declaration function declarations and other actions to execute the operation var num;   function Func1 () {} var Func2, assignment of code execution phase variables, invocation of functions, etc. execution statements belong to Operation Console.log (NUM) executed during the code execution phase;   Num=1;   Func1 ();   Func2 (); Func2=function () {};
console.log (num); var num=1; func1 ();   function func1 () {}func2 ();   var func2=function () {}

arguments Object1. The function is used to save all arguments of a function >>> but when the function exists, you can use the array subscript to access the number of elements in all arguments >>>alert (arguments[4]) 2.arguments of the function, depending on the argument list, Independent of the number of formal parameters 3. Once the function is called, the arguments are passed in, and the corresponding bits of the parameters are bound to modify the parameters corresponding to the arguments elements, and the corresponding elements in the arguments will be changed, but the opposite is also true. Then the parameters and arguments of the position will not be associated 4.arguments.callee (); a reference to the current function is executed to invoke itself in the function using recursionBOM Screen Object
Console.log (Window.screen); console.log (screen); Console.log (screen.width); Console.log (screen.height); Console.log (screen.availwidth); // Usable width console.log (screen.availheight); // available height =screen.height-bottom taskbar height

Location Object
// full URL path console.log (location.protocol);        // Agreement name console.log (location.hostname);     // Host name // Port number // Host name + port number Console.log (location.pathname);     // file path // starting with the parameters section // anchor position starting from #

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

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

Jump page, no fallback button after loading new interface, unable to return
function Gotobaidubyreplace () {location.replace ("http://www.baidu.com");}

Refresh the current page
location.reload (); Refresh the page  if there is a cache locally, the  equivalent of pressing f5location.reload (TRUE) will be read from the cache; forced flush  , regardless of cache , the latest data is loaded in the background, which is equivalent to Ctrl+f5

History Object
Console.log (history); Console.log (history.length); // the number of history pages used to record the current page jump

Click to go to the previous page equivalent to the browser's forward button
function forward () {History.forward ();}

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

Any interface that jumps to the browsing history +1 means the previous page-1 means that the next page 0 means the current page so History.go (0); equivalent to refreshing the page
function Go () {history.go ();}

Navigator ObjectReturns various system information about the browser console.log (navigator); All plugins for the output browser
 for (var i=0;i<navigator.plugins.length;i++

Common methods for window objects①prompt () Pop-up window input ②alert () Pop-up window output ③confirm () to be determined to remove the prompt box to return true False④close () Close the current browser window ⑤open () Open a new window parameter address parameter two new window The name of the mouth is nothing. Parameters three new windows of various configuration properties Scrollbars=yes indicates whether to display scroll bar only in IE useful window.open ("http://www.baidu.com", "Baidu", "width=600px, height=  600px,top=100px,left=100px,scrollbars=yes "); ⑥settimeout delay, which indicates how much delay the MS executes a function parameter one can pass in an anonymous function, you can pass in the function name parameter two delay of the number of milliseconds parameter three to the parameter n to the callback function parameter SetTimeout (function (num1,num2) {},20 00, "hahaha", 123,456,47) the ⑦setinterval timer indicates how many MS executions are performed once the other usage is exactly the same as settimeout ⑧clearinterval clear Timer ⑨cleartimeout Clear delay Timer sound Can accept the returned ID and return the ID to clearinterval to clear thenumber of DOM nodesDOM nodes are divided into three categories of element nodes (label nodes) attribute node text node attribute node text nodes are child nodes of the element node, so when you do so, you need to select the element node and then modify the properties and text viewing ELEMENT nodes1. Using the GetElement series method
var  Li=document.getelementbyid ("First")var  list1=document.getelementsbyclassname ("CLS")  var  list2=document.getelementsbyname ("name")var  list3= document.getElementsByTagName ("Li")

Note ①id cannot be the same name if the ID is duplicated, only the first ② gets the element node, you must wait until the DOM tree is loaded to obtain two ways to write JS in the document at the end of the code written to the Window.onload function ③ through the GetElements series to the array format,  Each of these elements must be taken in order for the operation to be performed, but not to operate directly on the array document.getelementsbyclassname ("CLS"). Click () =function () {}; Error Document.getelementsbyclassname ("CLS") [0].click () =function () {}; Correct ④ This series of methods, you can also first select a DOM node, from the selected DOM node, select the desired node document.getElementById ("First"). getElementsByTagName ("Li"); 2. Through the Queryselector series method ① Pass in a selector name, return the first found element, usually used to find ID var dq1=document.queryselector ("#id") ② passed in a selector name, Returns all found elements no matter how many are found, returns the array format var dqs1= document.queryselectorall ("#div1 li") View Modify Properties nodeView the Properties node. getattribute ("property name") sets the attribute node. SetAttribute ("Property name", "property value") Considerations. SetAttribute () There is a compatibility problem with the old version of IE, you can use the. Symbol instead
document.getElementById ("First"). Classname= "haha";

js Modify CSS in a variety of ways1. Set class and style using SetAttribute
document.getElementById ("First"). SetAttribute ("Class", "Class1") document.getElementById ("first"). SetAttribute ("Style", "color:red")

2. Add a class selector using the. classname
document.getElementById ("First"). Classname= "Class1"

3. Modify a single style directly using the. Style name, and note that the style name must use the Hump naming method
document.getElementById ("First"). style.color= "Red";d Ocument.getelementbyid ("First"). Style.fontsize= " 18px ";

4. Add a serial-level style using the. style or. style.csstext
  document.getElementById ("First"). style= "color:red";   // IE not compatible  document.getElementById ("First"). style.csstext= "color:red";

View Settings Text node. innerHTML fetching or setting HTML code in a node
document.getElementById ("First"). Innerhtmldocument.getelementbyid ("First"). Innerhtml= "<a href=" >hah</a> "

. innertext fetching or setting text in a node, cannot set HTML code
document.getElementById ("First"). InnerText

Hierarchical node Operations1. ChildNodes gets all the child nodes of the current node including the element node and the text node. Children gets all elements of the current node child nodes do not include text Node 2. . parentnode gets the parent node of the current node 3. . FirstChild Gets the first child node that includes a text node such as a carriage return. Firstelementchild gets the first element node without a text node. lastchild. Lastelementchild gets the last 4.   . PreviousSibling gets the previous sibling node of the current node, including the text node. Previouselementsibling Gets the previous element sibling node of the current node. nextSibling. nextelementsibling    Gets the latter one 5. . Attributes gets all the property nodes of the current node return array format Create and add a node1. Document.createelement ("tag name") Creates a new node and returns the new node that is created. SetAttribute set properties for the new node 2. Parent node. insertbefore (new node, target node) The parent node before the new node is inserted into the target node in the parent node. appendchild (new node) inside the parent node Finally, insert a new node 3. The source node. CloneNode () clones a node into true to indicate that the clone source node and all child nodes of the source node are passed in False or not, which means that only the current node is cloned and no child nodes are cloned Delete a replacement node1. 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

JavaScript basics and functions, bom,dom node and DOM node operations

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.