search
HomeWeb Front-endJS Tutorial100 commonly used js functions and syntax

100 commonly used js functions and syntax

Apr 10, 2018 pm 02:32 PM
javascriptfunctiongrammar

The content of this article is to share with you 100 commonly used js functions and syntax, which has a certain reference value. Friends in need can refer to it

Website special effects are inseparable from scripts, and javascript is the most commonly used Scripting language, let’s summarize the commonly used basic functions and syntax:

1. Output statement: document.write("");
2. The comments in JS are //
3. The traditional HTML document sequence is: document->html->(head,body)
4. DOM in a browser window The order is: window->(navigator, screen, history, location, document)
5. Get the name and value of the element in the form: document.getElementById("The name and value of the element in the form ID number").name (or value)
6. A lowercase to uppercase JS: document.getElementById("output").value = document.getElementById("input").value. toUpperCase();
7. Value types in JS: String, Number, Boolean, Null, Object, Function
8. Convert character type to numeric type in JS: parseInt(),parseFloat()
9. Convert numbers in JS to character type: ("" variable)
10. Get the string length in JS: (length)
11. Characters in JS are connected with characters using symbols.
12. The comparison operators in JS are: == equal to, != not equal to, >, >=, <.>13. Use: var to declare variables in JS
14. Judgment statement structure in JS: if(condition){}else{}
15.JS Loop structure: for([initial exPRession];[condition];[upadte expression]) {inside loop}
16. The command to terminate the loop is: break
17. Function definition in JS: function functionName([ parameter],...){statement[s]}
18. When multiple forms appear in the file, you can use document.forms[0], document.forms[1] instead.
19 .Window: open the window window.open(), close a window: window.close(), the window itself: self
20. Status bar settings: window.status="character";
21. Pop-up prompt Information: window.alert("character");
22. Pop up the confirmation box: window.confirm();
23. Pop up the input prompt box: window.prompt();
24. Specify the current display Link location: window.location.href="URL"
25. Get the number of all forms in the form: document.forms.length
26. Close the document's output stream: document.close();
27. String append connector: =
28. Create a document element: document.createElement(), document.createTextNode()
29. Method to get the element: document.getElementById()
30. Set the values ​​of all text members in the form to be empty:

var form = window.document.forms[0]for (var i = 0; i


31. Determine whether the check button is selected in JS: document.forms[0].checkThis.checked (the checked attribute represents whether it is selected and returns TRUE or FALSE)
32. Radio button group ( The names of the radio buttons must be the same): Take the length of the radio button group document.forms[0].groupName.length
33. The radio button group is also used to determine whether it is selected. checked.
34. Drop-down list Box value: document.forms[0].selectName.options[n].value (n sometimes uses the name of the drop-down list box plus .selectedIndex to determine the selected value)
35. Definition of string: var myString = new String("This is lightsWord");
36. Convert the string to uppercase: string.toUpperCase(); Convert the string to lowercase: string.toLowerCase();
37. Return string 2 in The position that appears in String 1: String1.indexOf("String2")!=-1 means it is not found.
38. Get a character at the specified position in the string: StringA.charAt(9);
39. Take out the substring of the specified starting point and end point in the string: stringA.substring(2,6);
40. Mathematical functions: Math.PI (returns pi), Math.SQRT2 (returns square root), Math .max(value1,value2) returns the highest value of the two numbers, Math.pow(value1,10) returns the tenth power of value1, Math.round(value1) rounding function, Math.floor(Math.random() *(n 1)) returns a random number
41. Define date type variable: var today = new Date();
42. Date function list:
dateObj.getTime() gets the time,
dateObj.getYear() gets the year,
dateObj.getFullYear() gets the four-digit year,
dateObj.getMonth() gets the month,
dateObj.getDate() gets the day,
dateObj.getDay () gets the date,
dateObj.getHours() gets the hours,
dateObj.getMinutes() gets the minutes,
dateObj.getSeconds() gets the seconds,
dateObj.setTime(value) sets the time ,
dateObj.setYear(val) sets the year,
dateObj.setMonth(val) sets the month,
dateObj.setDate(val) sets the day,
dateObj.setDay(val) sets the day of the week,
dateObj.setHours sets hours,
dateObj.setMinutes(val) sets minutes,
dateObj.setSeconds(val) sets seconds [Note: This date and time starts from 0]
43.FRAME Representation method:
[window.]frames[n].ObjFuncVarName,frames["frameName"].ObjFuncVarName,frameName.ObjFuncVarName
44.parent represents the parent object, top represents the top object
45.Open The parent window of the child window is: opener
46. Indicates the current location: this
47. When calling a JS function in a hyperlink, use: (javascript:) to start with the function name
48 .Do not execute this JS in old browsers:
49. Reference a file-style JS:
50. Specify the HTML displayed in browsers that do not support scripts:
51. When there are both hyperlinks and ONCLICK events, then Older versions of browsers will redirect to a.html, otherwise they will redirect to b.html. Example: dfsadf> ;
52.JS’s built-in objects include: Array, Boolean, Date, Error, EvalError, Function, Math, Number, Object, RangeError, ReferenceError, RegExp, String, SyntaxError, TypeError, URIError
53.JS Line break in:\n
54. Window full screen size:
<script>function fullScreen(){ this.moveTo(0,0);this.outerWidth=screen.availWidth;this.outerHeight=screen. availHeight;}window.maximize=fullScreen;</script>
55.all in JS represents all the elements below it http://bizhi.knowsky.com/
56.Focus order in JS: document.getElementByid("Form Element").tabIndex = 1
57.The value of innerHTML is the value of the form element: such as

"how are you "

, then the value of innerHTML is: how are you
58. The value of innerTEXT is the same as above, except that the tag will not be displayed Come out.
59.contentEditable can set whether the element can be modified, isContentEditable returns whether the element can be modified.
60.isDisabled determines whether it is a prohibited state. disabled sets the prohibited state
61.length gets the length and returns Integer value
62.addBehavior() is an external function file called by JS. Its extension is .htc
63.window.focus() puts the current window in front of all windows.
64. blur() means losing focus. It is the opposite of FOCUS().
65.select() means the element is selected.
66. Prevent the user from entering text in the text box: onfocus="this.blur()"
67. Get the number of times the element appears on the page: document.all.tags("p (or other HTML tag)").length
68. There are two types of form output in JS: module Modal and non-modal. window.showModaldialog(), window.showModeless()
69. Status bar text setting: window.status='text', default status bar text setting: window.defaultStatus = 'text. ';
70. Add to favorites: external.AddFavorite("http://www.xrss.cn","jaskdlf");
71. In JS, no operation is performed when a script error is encountered: window.onerror = doNothing; The syntax for specifying an error handle is: window.onerror = handleError;
72. In JS, specify the parent window of the currently open window: window. opener, supports multiple continuations of opener.opener...
73.self in JS refers to the current window
74.The content displayed in the status bar in JS: window.status="content"
75.top in JS refers to the top-level frame in the frame set
76.Close the current window in JS: window.close();
77.Propose a confirmation box in JS:if(confirm( "Are you sure?")){alert("ok");}else{alert("Not Ok");}
78.Window redirection in JS: window.navigate("http://www .sina.com.cn");
Print in 79.JS: window.print()
Prompt input box in 80.JS: window.prompt("message","defaultReply");
81.Window scroll bar in JS: window.scroll(x,y)
82.Window scroll to position in JS: window.scrollby
83.Set the time interval in JS: setInterval("expr ",msecDelay) or setInterval(funcRef,msecDelay) or setTimeout
84. The modal display in JS is in IE4, but not in NN: showModalDialog("URL"[,arguments][,features]);
85. The handle used before exiting in JS: function verifyClose(){event.returnValue="we really like you and hope you will stay longer.";}} window.onbeforeunload=verifyClose;
86.When the window The file handle used when the form is called for the first time: onload()
87. The file handle called when the form is closed: onunload()
88. The properties of window.location: protocol(http:),hostname (www.example.com),port(80),host(www.example.com:80),pathname("/a/a.html"),hash("#giantGizmo", refers to jumping to the corresponding anchor Note), href (all information)
89.window.location.reload() refreshes the current page.
89-1.parent.location.reload() refreshes the parent object (for frame)
89-2.opener.location.reload() refreshes the parent window object (for single window)
89-3.top.location.reload() refreshes the top object (for multiple windows)
90.window.history.back() returns to the previous page, window.history.forward() returns to the next page, window.history.go (returns to which page, you can also use the visited URL)
91. document.write() output without line breaks, document.writeln() output with line breaks
92.document.body.noWrap=true; prevent link text from wrapping.
93.Variable name.charAt(number) , take the character of the variable.
94. "abc".charCodeAt (number of characters), return the ASCii code value of the character of the variable.
95. String concatenation: string.concat( string2), or use = to connect
96. Variable.indexOf("Character", starting position), returns the first appearing position (calculated from 0)
97.string.lastIndexOf(searchString[ ,startIndex]) The position where the last occurrence occurred.
98.string.match(regExpression), determine whether the characters match.
99.string.replace(regExpression,replaceString)Replace the existing string.
100 .string.split (separator) returns an array storage value.
101.string.substr(start[,length]) takes the string from the number to the specified length.
102.string.toLowerCase( ) changes all characters to lowercase.
103.string.toUpperCase() changes all characters to uppercase.
104.parseInt(string[,radix(representing base)]) forces conversion to an integer.
105.parseFloat(string[,radix]) is forced to convert to a floating point type.
106.isNaN (variable): Test whether it is a numeric type.
107.Keywords for defining constants: const, definition Keywords for variables: var

The above is the detailed content of 100 commonly used js functions and syntax. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor