JavaScript, like HTML and CSS, is the three necessary modules for Web front-end development. In addition, JavaScript is also the basic language of Vue, Ext, jQuery and other frameworks, so the learning of JavaScript is crucial. In fact, after learning the C + + language and Java, I feel that the basic syntax of JavaScript is similar to that of Java, so I don't remember the basic syntax of the input-output loop statement. After all, the code is written every day, and I won't forget it.
As I summarized HTML and CSS before, I also stood in the perspective of undergraduate application layer, focusing on more commonly used syntax collocations, followed by those with fancy functional syntax, omitting those old methods that can be replaced by new functions.
HTML section: click here
Part CSS: click here
Contents:
Catalog
Part one: the most commonly used grammar
Common debugging methods,Eight methods of getting HTML components,data type,Button method binding,Array / loop,Common methods of array,Common methods of string,With HTML components
Part II: other small functions
Timed execution function,Dynamic update time component,regular expression ,Input bar prompt text,exception handling,Rolling title,JSON,Simulate Java classes,Using JS to add HTML components,Table data adding
Part one: the most commonly used grammar
Common debugging methods
alert('hello zwz');//Elastic frame console.log('hello zwz!');//Debug window document.getElementById('c').innerHTML = 'hello zwz';//Overwrite output to HTML element //You can change = to + = without overwrite
Eight methods of getting HTML components
<input id="did" class="dclass" name='dname' value="aaa"/> //HTML above var did = document.getElementById('did');//Find unique by ID var dclass = document.getElementsByClassName('dclass')[0]; //Find not unique by class var ddiv = document.getElementsByTagName('input')[0]; //Find not unique by tag name var dclass2 = document.getElementsByName('dname')[0]; //Find not unique by name var b = document.querySelector('#did').value; //id var c = document.querySelector('.dclass').value;//class var d = document.querySelector('input').value; // Label var e = document.querySelectorAll('input')[0].value; //All label sets
data type
JavaScript is a weakly typed language. In C + +, if an int type variable is output in% f format, it will make mistakes, and vice versa; this is because there is an insurmountable gap (personal understanding) between integer and floating-point number. It's different in JavaScript. var is a versatile type. Integers, floating-point numbers, strings, even objects and arrays can be defined in general. Of course, you can use the typeof function to get the current data type, like this:
var a = 1; var b = 3.14; // num.toFixed(4); four bits reserved var c = 'hello zwz!'; var d = ['zwz01','zwz02','zwz03']; var e = { 'name':'zwz', 'age':18 }; var leixing = typeof(a); var num = parseFloat(string);//String to Num
If var is the only variable not initialized, the type is undefined; if it is empty, it is Null; if the number calculation result is not a number, it is NaN.
Button method binding
<input type="button" value="Button" οnclick="run()"/> function run(){ //Running code }
Array / loop
//One-dimensional array var arr = ['a1','a2','a3','a4','a5','a6']; //Two-dimensional array var arr = [ ['zwz01','zwz02','zwz03'], ['zwz11','zwz12'] ]; alert(arr[0][1]);//call //for-in Loops var a = [3,4,5,6,7]; for(var i in a){ document.getElementById('d').innerHTML += i+'<br>'; }
Common methods of array
Common methods of string
With HTML components
//<! -- drop down menu -- > var se = document.getElementById('se').value; //<! -- single / mu lt iple box -- > var form = document.getElementById('fo').lag;//lag is the name attribute for(var i = 0 ; i < form.length; i ++){ if(form[i].checked){ console.log(form[i].id);break;//operation } form[i].checked = 1; // All election if(form[i].checked) //Counter election 1 form[i].checked = 0; else //Counter election 2 form[i].checked = 1; }
Part II: other small functions
Timed execution function
var temp; function run(){ console.log('zwz One second has passed<br>'); } function start(){ temp = window.setInterval('run()',1000); } function stop(){ window.clearInterval(temp); }
Dynamic update time component
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <body οnlοad="retime()"> <div id="d"></div> </body> </html> <script> function retime(){ var time = new Date(); var year = time.getFullYear(); var mouth = time.getMonth() + 1; var date = time.getDate(); var hour = time.getHours(); var min = time.getMinutes(); var sec = time.getSeconds(); document.getElementById('d').innerHTML = year + 'year' + mouth + 'month' + date + 'day ' + hour + ': ' + min + ': ' + sec; var thread = setTimeout('retime()',1000); } </script> <style type="text/css"> div{ height: 200px; width: 1200px; background-color: gainsboro; } </style>
regular expression
function run(){ var input = document.getElementById('in').value; // console.log(typeof(input)); if(!( /^[a-zA-Z]\w{3,15}$/.test(input))){ console.log('Incorrect input'); } }
Input bar prompt text
<input type="text" id="in" value="Please input" /> var input = document.getElementById('in'); input.onmouseup = function(){this.focus();} input.onfocus = function(){this.select();};
exception handling
For example, I write an extra t on the alert function in the code. If there is no exception, I will directly report an error on the browser debugging page. If there is a catch statement, I will print the error information in the HTML element with id 'd'.
function run(){ try{ alertt('hello zwz'); }catch(e){ document.getElementById('d').innerHTML = e.message; } }
Rolling title
The principle of implementation is to put the last letter at the front every other short period of time to simulate the rolling effect.
<script> var str = 'hello zwz!'; function run(){ document.title = str; str = str.substring(1,str.length) + str.substring(0,1); } setInterval('run()',200); </script>
JSON
In addition, there is a JSON pattern that needs to be studied. This is the format that the front end must convert to the back end.
If it is defined in the Java class of the backend as follows: (use var to simulate the backend Java class)
var a = { 'people':[ {'name':'zwz01','age':'18'}, {'name':'zwz02','age':'19'} ] };
Then, the JSON mode is as follows:
var b = '{ "people" : [' +'{ "name":"zwz01" , "age":"18" },' +'{ "name":"zwz02" , "url":"19" }'+']}'; var result1 = typeof(b);//Result is of type string
To put it bluntly, it is to enclose the brace {}. At this time, the data type of b is string string type.
Then we use the JSON.parse function to transform
var c = JSON.parse(b); var result2 = typeof(c);//Result is object type alert(c.people[0].name);//Quote
This shows that c is an object type, which converts strings into an object model. You can also use the elements directly
As for the conversion of object type to string, I will check it later.
Simulate Java classes
function People(name,age){ this.name = name; this.age = age; this.say = function(){ console.log(this.name + ' is ' +this.age + ' years old!'); } } var p1 = new People('zwz01',18); p1.say();
Using JS to add HTML components
//Suppose there is a ul with id 'u' in < body > <script> var LiArray = document.getElementById('u').getElementsByTagName('li'); var aNew = document.createElement('a'); var aNewText = document.createTextNode('Baidu'); var aNewHref = document.createAttribute('href'); aNewHref.value = 'http://www.baidu.com'; aNew.setAttributeNode(aNewHref); aNew.appendChild(aNewText); LiArray[0].appendChild(aNew); var Body = document.body; var HrNew = document.createElement('hr'); var HrColor = document.createAttribute('color'); HrColor.value = 'red'; HrNew.setAttributeNode(HrColor); Body.appendChild(HrNew); </script>
Table data adding
<body> <table id="msg" align="center"> <caption>XXXX surface</caption> <tr> <td>Student ID</td><td>Full name</td><td>Gender</td> </tr> <input type="button" οnclick="addRow()" value="Add data"/> </table> </body> <script> function addRow(){ var form = document.getElementById('msg'); var newRow = form.insertRow();//Return the newly inserted row (deleteRow(index) delete) newRow.insertCell(0).innerHTML = '0413170337'; newRow.insertCell(1).innerHTML = 'zwz'; newRow.insertCell(2).innerHTML = 'nan'; } </script>
Last edited January 30, 2020