Home Web Front-end JS Tutorial An introduction to the basics of js syntax for beginners

An introduction to the basics of js syntax for beginners

Jun 16, 2017 am 10:16 AM
js programming

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>
Copy after login

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;
}
Copy after login
//函 数 名: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);
}
Copy after login

以上就是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 of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use JS and Amap to display the boundaries of administrative districts in locations How to use JS and Amap to display the boundaries of administrative districts in locations Nov 21, 2023 am 08:44 AM

How to use JS and Amap to realize the function of displaying the boundaries of administrative districts of locations. With the development of the Internet, map services have gradually become an indispensable part of people's daily lives. In web development, we often need to use map API to display geographical location information. This article will introduce how to use JS and Amap to implement the location administrative district boundary display function, and provide specific code examples. Preparation work First, we need to register a developer on the AMAP open platform (https://lbs.amap.com/)

How to use JS and Baidu Maps to implement map tile loading function How to use JS and Baidu Maps to implement map tile loading function Nov 21, 2023 pm 02:45 PM

How to use JS and Baidu Map to implement the map tile loading function. Baidu Map is a very popular map application that provides a wealth of map services and functions. Map tile loading is a commonly used function in Baidu Maps. It can divide a large picture into many small tiles and then load them on demand to achieve smooth display of the map. This article will introduce how to use JS and Baidu Map API to implement the map tile loading function, and give specific code examples. Get map tiles First, we need to get map tiles. Baidu Map provides

How to use JS and Baidu Maps to implement map marker aggregation function How to use JS and Baidu Maps to implement map marker aggregation function Nov 21, 2023 pm 05:24 PM

How to use JS and Baidu Maps to implement the map marker aggregation function. The map marker aggregation function is one of the common functions in modern map applications. It can help users view a large number of marker points on the map more clearly and reduce the number of marker points on the map. , to avoid problems such as marking points being too dense and making it impossible to see the specific location clearly. This article will introduce how to use JS and Baidu Maps to implement the map mark aggregation function, and provide specific code examples. First, we need to understand some necessary prerequisite knowledge. Baidu Map API: Baidu Map provides a wealth of

How to use JS and Amap to implement the location heat map function How to use JS and Amap to implement the location heat map function Nov 21, 2023 pm 01:30 PM

How to use JS and Amap to implement the location heat map function. With the popularity of the Internet and mobile devices, people's demand for geographical location information is getting higher and higher. Location heat maps can visually display the heat distribution of various locations in a certain area, helping us better understand data and trends. This article will introduce how to use JS and Amap to implement the location heat map function, and provide specific code examples. 1. Preparation work Before implementation, we need to complete the following preparation work: register an account on the Gaode open platform and apply for relevant APIs to introduce Gaode

How to use JS and Baidu Maps to add custom text annotations to the map How to use JS and Baidu Maps to add custom text annotations to the map Nov 21, 2023 pm 06:12 PM

How to use JS and Baidu Maps to implement the function of adding custom text annotations to maps. Maps are a commonly used function in modern web development, and Baidu Maps, as one of the most popular map services in China, provides a wealth of interfaces and functions to satisfy development needs. the needs of the users. This article will introduce how to add custom text labels on the map by using JavaScript and Baidu Map API, and attach specific code examples. 1. Preparation work First, we need to introduce the Java of Baidu Map API into the HTML code

How to use JS and Baidu Maps to implement map POI search function How to use JS and Baidu Maps to implement map POI search function Nov 21, 2023 pm 05:26 PM

How to use JS and Baidu Maps to implement the map POI search function. With the rapid development of the mobile Internet, the map navigation function has become one of the important functions in mobile applications. In realizing the map navigation function, POI (Points of Interest) search is an essential function. Through POI search, users can quickly locate places of interest on the map, such as restaurants, hotels, gas stations, etc. In this article, we will introduce how to use JS and Baidu Map API to implement map POI search

How to use JS and Baidu Maps to implement map marker aggregation function How to use JS and Baidu Maps to implement map marker aggregation function Nov 21, 2023 pm 05:24 PM

How to use JS and Baidu Maps to implement the map marker aggregation function. The map marker aggregation function is one of the common functions in modern map applications. It can help users view a large number of marker points on the map more clearly and reduce the number of marker points on the map. , to avoid problems such as marking points being too dense and making it impossible to see the specific location clearly. This article will introduce how to use JS and Baidu Maps to implement the map mark aggregation function, and provide specific code examples. First, we need to understand some necessary prerequisite knowledge. Baidu Map API: Baidu Map provides a wealth of

How to use JS and Baidu Maps to implement map ranging function How to use JS and Baidu Maps to implement map ranging function Nov 21, 2023 pm 12:26 PM

How to use JS and Baidu Maps to implement the map distance measurement function requires specific code examples. The map distance measurement function is to measure the distance between two points on the map. In front-end development, you can use JS combined with Baidu Map API to implement this function. First, we need to introduce the API library of Baidu Maps. It can be introduced by adding the following code in the HTML file: &lt;scriptsrc="http://api.map.baidu.com/api?v=2.0&

See all articles