search
HomeWeb Front-endJS TutorialAn introduction to the basics of js syntax for beginners

With the popularity of ajax, js has attracted a lot of attention. The biggest advantage of js is that it can operate on all elements on html, including creating label elements, changing element attributes, etc., which allows us to use js to achieve many dynamic effects and provide users with stronger interactivity!

An introduction to the basics of js syntax for beginners

Js test method

In debugging When writing Javascript scripts, if there is an error, there will be a question mark in the status bar of IE [click this question mark], or an error box will pop up. In order to find the error as soon as possible, the following are commonly used debugging methods:
1. If the object appears null or the object cannot be found, it means that the id, name or DOM is written incorrectly. Please check the line where the error is located;
2.If the error is located in a function call, it means that the function body has If there is a problem, go to the function body to find the reason.
3.In order to speed up, you can first use /* */ comments to block part of the code and check it step by step;
4.You can add alert(xxx) to see See if the variable has the expected value;
5.IE error reports are often inaccurate. For example, if line 18 is wrong, sometimes there is a problem with line 19;
6. In order to ensure that the code can run correctly, when you are really not sure whether an error will occur, use the try{}catch{} statement to do other methods. Please continue to add.

 <script>   
  try{   
        x=y;       //   Cause   an   error.   
  }   
  catch(e){       //   Create   local   variable   e.   
        alert(e);       //   Prints   "[object   Error]".   
        alert(e.number   &   0xFFFF);       //   Prints   5009.   
        alert(e.description);       //   Prints   "&#39;y&#39;   is   undefined".   
  }   
  </script>

Every item is a small skill in js, but it is very practical!
1.document.write(""); Output statement
2. The comment in JS is //
3. The traditional HTML document sequence is: document->html-> (head,body)
4. The DOM order in a browser window is: window->(navigator, screen, history, location, document)
5. Get the name and value of the element in the form: document .getElementById("ID number of the element in the form").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 types into numerical types in JS: parseInt(), parseFloat()
9. Convert numbers in JS to character type: (""+variable)
10. The length of string in JS is: (length)
11. Characters in JS are connected to characters Use the + sign.
12. The comparison operators in JS are: == equal to, != not equal to, >, >=, <.>13. To declare variables in JS: var to declare
14. Judgment statement structure in JS: if(condition){}else{}
15. Loop structure in JS: 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(), window itself: self
20. Status bar setting: window.status="character";
21. Pop-up prompt message: window.alert("character");
22. Pop-up Confirmation box: window.confirm();
23. Pop up the input prompt box: window.prompt();
24. Specify the location of the currently displayed link: window.location.href="URL"
25 .Get the number of all forms in the form: document.forms.length
26. Close the output stream of the document: 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-type members in the form to empty:
var form = window.document.forms[0]
for (var i = 0; i if (form.elements.type == "text"){
form.elements.value = "" ;
}
}
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. Checked.# is also used to determine whether the radio button group is selected. ##34. The value of the drop-down list box: 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. Characters Definition of string: var myString = new String("This is lightsword");
36. Convert string to uppercase: string.toUpperCase(); Convert string to lowercase: string.toLowerCase();
37 .Return the position where string 2 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. Math functions: Math.PI (returns pi), Math.SQRT2( Returns the 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 variable: var today = new Date();
42. List of date functions: 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() Get 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 the hours, dateObj.setMinutes(val) sets the minutes, dateObj.setSeconds(val) sets the seconds [Note: This date and time starts from 0]
43.FRAME representation: [window.]frames[n].ObjFuncVarName,frames["frameName"].ObjFuncVarName,frameName.ObjFuncVarName
44.parent represents the parent object, top represents the top object
45. The parent window that opens the child window is: opener
46. Indicates the current location: this
47. When calling a JS function in a hyperlink, use: (javascript:) to start and add the function name
48. This JS will not be executed in old browsers:
49. Quote 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, the old version of the browser will redirect to a.html, otherwise it will redirect to b.html. Example: dfsadf
52. The built-in objects of JS are: Array, Boolean, Date, Error, EvalError, Function, Math, Number, Object, RangeError, ReferenceError, RegExp, String, SyntaxError, TypeError, URIError
53.Line break in JS:\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 elements below it
56.Focus order in JS: document.getElementByid("Form element ").tabIndex = 1
57.The value of innerHTML is the value of the form element: If then the value of innerHTML is: how are you
58.The value of innerTEXT is the same as above, except that this will not be changed The mark is displayed.
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 , returns an 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. 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 forms of output in JS :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.dannyg.com","jaskdlf");
71.Do nothing when a script error is encountered in JS Operation: window.onerror = doNothing; The syntax for specifying an error handle is: window.onerror = handleError;
72. Specify the parent window of the currently opened window in JS: window.opener, supporting 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 window in the frame set Top-level framework
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");
79.Print in JS: window.print()
80.Prompt input box in JS: window.prompt("message","defaultReply");
81.Window scroll bar in JS: window .scroll(x,y)
82.Scroll the window to the 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. The file handle used when the form is called for the first time: onload ()
87. File handle called when the form is closed: onunload()
88. 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),href(all information)
89.window.location.reload() refreshes the current page.
90.window.history.back() returns to the previous page, window.history.forward() returns to the next page, window.history.go(returns to the Several pages, 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 being folded Line.
93.Variable name.charAt(number), get the character of the variable.
94."abc".charCodeAt(number), return the ASCii of the character Code value.
95. String connection: string.concat(string2), or use += to connect
96. Variable.indexOf("character", starting position), returns the first occurrence position (Calculated from 0)
97.string.lastIndexOf(searchString[,startIndex]) The last occurrence of the position.
98.string.match(regExpression), determine whether the characters match.
99.string .replace(regExpression,replaceString) replaces the existing string.
100.string.split(separator) returns an array to store the value.
101.string.substr(start[,length]) takes from which to a string of specified length.
102.string.toLowerCase() changes all characters to lowercase.
103.string.toUpperCase() changes all characters to uppercase.
104.parseInt( string[,radix (representing base)]) is forced to be converted into an integer type.
105.parseFloat(string[,radix]) is forced to be converted into a floating point type.
106.isNaN(variable): Test whether it is Numerical type.
107. Keywords for defining constants: const, keywords for defining variables: var

有用的js程序代码:

//去左空格;
function ltrim(s){
return s.replace( /^\s*/, "");
}
//去右空格;
function rtrim(s){
return s.replace( /\s*$/, "");
}
//左右空格;
function trim(s){
return rtrim(ltrim(s));
}
//检查非法字符
//str 要检查的字符
//badwords 非法字符 &|<>=
function checkbadwords(str, badwords) {
if (typeof (str) != "string" || typeof (badwords) != "string") {
return (false);
}
for (i=0; i bad = badwords.charAt(i);
for (j=0; j if (bad == str.charAt(j)) {
return false;
break;
}
}
}
return true;
}
//检查合法字符,限制只能输入的字符
//str 要检查的字符
//goodwords 合法字符 1234567890abcdefghijklmnopqrstuvwxyz
function checkgoodwords(str, goodwords) {
if (typeof (str) != "string" || typeof (goodwords) != "string") {
return (false);
}
for (i=0; i this_str = str.charAt(i);
for (j=0; j if (this_str == goodwords.charAt(j)) {
break;
}
if(j==goodwords.length-1){
return false;
}
}
}
return true;
}
//函 数 名:chkinteger
//功能介绍:检查是否为数字
//参数说明:要检查的字符串
//返 回 值:false:不是 true:是
function chkinteger(checkStr) {
var checkOK = "0123456789+-";
var allValid = true;
for (i=0; i ch = checkStr.charAt(i);
if (checkOK.indexOf(ch) == -1) {
allValid = false;
break;
}
if ((ch == &#39;+&#39; || ch == &#39;-&#39;) && i>0) {
allValid = false;
break;
}
}
return (allValid);
}
//函 数 名:chklength
//功能介绍:检查字符串的长度
//参数说明:要检查的字符串
//返 回 值:字节长度值
function chklength(checkStr) {
var n = 0;
for (i=0; i chcode = checkStr.charCodeAt(i);
if (chcode>=0 && chcode<=255) {
n++;
} else {
n += 2;
}
}
return (n);
}

以上就是js入门基础编程的全部内容了,感谢大家的阅读!

The above is the detailed content of An introduction to the basics of js syntax for beginners. 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
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

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 Article

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor