search
HomeWeb Front-endJS TutorialThe most systematic summary of the key points of JavaScript (excluding basic language syntax)

1, variable
1. You can use new Array ("1", "2"); to define an array.
2. You can clear variables by assigning null to them, such as:

//首先定义一个变量
var i1=10;
i1=null;
//此时的i1就被清除了

Be careful when defining variables in functions like this

funtion demo(){
     x=10;
}
//而此前的代码中都没有出现x,那么这里就是定义了x,在调用demo函数以后,x就是一个全局变量了。

2. Operators == and = ==

var i="5";
var j=5;
if(i==j) alert(""hello);
if(i===j) alert("world");

//The above code will only pop up hello after running, because the values ​​​​of i and j are equal, but the data types of i and j are not equal. So == only requires equal values, but === not only requires equal values ​​but also requires equal data types.

Three, exception capture

try{
     if() throw "";
}catch(err){
     alert(throw);
}

Four, event
onload web page loading event
onclick click event
onfocus cursor gathering event
onselect text box selection event
onmouseover mouse over event
onmouserout mouse out event

5, dom operation
1, introduction: When the web page is loaded, the browser will create the document object model of the page.

2. DOM operation HTML
1) js can change all HTML elements in the page
①Change the output stream: document.write(); will overwrite all the contents of the document! Use with caution!
② Obtain elements: document.getElementById();
document.getElementByClass();
document.getElementByTagName(); etc.

Among them, tagname and this may get many Method of each element, the obtained elements become an object array, arranged in order

document.getElementById("btn").addEventListener("click",function(){
  var x=document.getElementsByName("people");
  var y=x[2].value;
  alert(y);
  });

③Change the Html content: innerHTML;
④Change the attribute content: After obtaining the object.Attribute = "Attribute value" then Yes, you can also use the setAttribute() method: the first parameter is the attribute name, and the second parameter is the attribute value
document.getElementById("pid").setAttribute("class","pid2");

The method of obtaining attribute values ​​uses getAttribute();

alert(document.getElementById("name").getAttribute("name"));

Some methods of dom controlling html:

          1,设置属性:如var attr=document.getElementById("demo1");
                              attr.setAttribute("title","dhello");//设置属性
                              var st=attr.getAttribute("title");//得到属性

                              alert(st);


          2.得到子节点:
                         var child=document.getElementsByTagName("ul")[1].childNodes;
                         alert(child.length);


          3得到父节点: var parent=document.getElementsByTagName("li")[0].parentNode;
                          alert(parent.nodeName);

          4创建元素节点:   var body=document.body;
                         var inp=document.createElement("input");//创建一个input节点
                         inp.type="button";//节点类型
                         inp.value="ann";
                         body.appendChild(inp);//把新的子节点添加到指定节点。(添加到末尾 )

          5创建文本节点


          6删除子节点:<p id="p1">
                         <p id="p1">这是一个段落。</p>
                         <p id="p2">这是另一个段落。</p>
                         </p>

                         var parent=document.getElementById("p1");//找到 id="p1" 的元素:

                         var child=document.getElementById("p1");//找到 id="p1" 的 <p> 元素:

                         parent.removeChild(child);//从父元素中删除子元素:


                         第二种方法:var child=document.getElementById("p1");
                                       child.parentNode.removeChild(child);


          7动态添加节点(课选择添加的位置)
                                       var p=document.getElementById("p");
                                       var node=document.getElementById("pid");
                                       var newnode=document.creatElement("p");
                                       p.inserBefore(newnode,node);
                                                      要添加的 在这之前的

2) js can change all HTML attributes in the page
< ;!DOCTYPE HTML>

 <title>hello world</title>


 <a id="aid"/>
 <p id=pid>hello world!!</p>

<script></script>

 document.getElementById("aid").href="www.baidu.com";//改变属性值



3) js can change all CSS styles in the page

document.getElementById("pid").style.backgrouneColor="red";

4) js can react to all events in the page

5) DOM object controls HTML

6. Event handle EventListener
Event handle is an action that triggers an event. For example, onclick is the handle when it is clicked.
Event handles can be added in js, which can reduce a lot of code.
For example, the following is the traditional event triggering method

The event handle added in the js code is as follows: the processing function cannot add () brackets!
var x=document.getElementById("btn");
x.addEventListener("click",demo);//There are two parameters here, one is the handle of the event, and the latter is the function that handles the event

To delete a handle, use removeEventListener();

Seven, events
1. Event flow: The order in which events are accepted on the page. There are two orders, namely event bubbling (from inside to outside), event capture (from outside to inside).

2. Event processing:
1) HTML event processing: directly added to the HTML structure

<button onclick="demo()"><button>

2) DOM level 0 event processing: assign a function to an event handler Attribute

<button id="btn"></button>
<script>
var btn1=document.getElementById("btn");
btn1.onclick= function () {
    document.getElementById("pid").style.backgroundColor="red";
};     
</script>

//Level 0 event processing Clear event processing is very simple, just assign onclick to empty. When setting, the time of the object is set to null instead of the object!
btn1.onclick=null;

//When there are multiple handlers for the same event, the previous one will be cleared by the later event handler.

btn1.onclick= function () {
    document.getElementById("pid").style.backgroundColor="red";//被覆盖
};
btn1.onclick= function () {
    document.getElementById("pid").style.backgroundColor="blue";
};

3) DOM level 2 event processing:

 addEventListener("事件名",“事件处理函数”,“true/false”);

true: event capture
false: event bubbling
To clear event processing, use removeEventListener();

//dom Level 2 event handlers will not be overwritten but will be parsed and executed step by step.

4) IE event handler. (Used in versions less than or equal to IE8, similar to the use of addEventListener.)

Add an event attachEvent
Delete an event detachEvent

5) It can be different according to the browser version Write different codes

if(btn.addEventListener){

     btn.addEventListener();
}
else{

     btn.attachEventListener()
}

3. Event object: An object will be generated when a dom event is triggered.

Attributes of the event object:
1) type: get the event type

document.getElementById("btn").addEventListener("click",showType);
function showType(e){
     alert(e.type);
}

2) target: get the event target: where this event is triggered, that is, the object of this event is an html element What elements in.

document.getElementById("btn").addEventListener("click",showTarget);
function showTarget(e){
     alert(e.target);
}

3) stopPropagation(): Prevent event bubbling: the innermost element event is triggered, but after this event occurs, the event of the upper element containing this element will also be triggered! So sometimes we don't want this to happen, which will prevent event bubbling from happening.
event.stopPropagation();

4) preventDefault(): Prevent event default behavior
event.preventDefault();

//dom 0级事件处理
//  var btn1=document.getElementById("btn");
//  btn1.onclick= function () {
//      document.getElementById("pid").style.backgroundColor="red";
//  };
//
//   btn1.onclick=null;
////dom 2级事件处理,处理函数不能加()括号符!
//

//var btn=document.getElementById("btn");
//btn.addEventListener("click",demo1);
//
//function demo1(){
//
//// alert("dom 2级事件处理!");
//
//   document.getElementById("pid").innerHTML="dom 2级事件处理!";
//}

//事件对象

//1.获取事件对象的类型

//document.getElementById("btn").addEventListener("click",showType);
//function showType(e){
//   alert(e.type);
//}

//2.获取事件对象的目标

//document.getElementById("btn").addEventListener("click",showTarget);
//function showTarget(e){
//   alert(e.target);
//}

八,内置对象
1.什么是对象:js中所有事物都是对象,例如字符串,数组,时间,数值,函数等,每个对象都会带有属性和方法;
2.创建对象:
1)使用new object创建
people=new objet();
people.name="krys";
people.age=20;
2)直接创建:
people={name:"krys",age:20,addres:"guangdong"};
3)使用函数创建

funtion people(name,age){
     this.name=name;this.age=age};
son=new people("jess",20);//然后创建一个对象

document.getElementById("btn").addEventListener("click",creat);
function people(name,age){
          this.name=name;
          this.age=age;
     }
 function creat(){
          var name1= document.getElementById("name").value;
          var age1=document.getElementById("age").value;
          son=new people(name1,age1);
          alert(son.name);
          alert(son.age);
          }

3.字符串对象:String:字符串可以使用双引号也可以使用单引号!

属性:length:str.length可得到字符串的长度、
 indexOf(),在字符串中查找字符串,并返回字符串所在的位置。

document.getElementById("btn").addEventListener("click",creat);
     function creat(){
          var name= document.getElementById("name").value;
          if(name.match("krys")){

              alert("r所在的位置是"+name.indexOf("r"));
          }else{
              alert("sorry~you didnt have rights!")
          }

          }

match(),在字符串中匹配字符串,如果字符串1在字符串中存在,则将字符串1打印出来,如果没有就返回NULL

document.getElementById("btn").addEventListener("click",creat);
     function creat(){
          var name= document.getElementById("name").value;
          if(name.match("krys")){
              alert(name);
          }else{
              alert("sorry~you didnt have rights!")
          }

          }

replace(a,b) a是要替换掉的原来的字符或字符串,b是新的字符或字符串

document.getElementById("btn").addEventListener("click",creat);
     function creat(){
          var name= document.getElementById("name").value;
          if(name.match("krys")){

              alert(name.replace("krys","krys小仙女"));
          }else{
              alert("sorry~you didnt have rights!")
          }

          }

toUpperCase()转换成大写
 toLowerCase()转换成小写
 split()分隔线,将一个字符串分隔成若干部分,如str="hello,world,welcome,to";var s=str.split(","); s[0]="hello";

4.Date对象
1)创建Date对象:
var date=new Date();
alert(date);
var h=date.getHours();//时
var m=date.getMinutes();//分
var s=date.getSeconds();//秒

2)获取具体年份:getFullYear();
3)获取毫秒数:getTime();
4)设置具体的日期:setFullYear();
5)获取星期:getDay();

6)设置每秒更新一次
setTimeout(function(){

 showTime();},1000);

//每秒调用一次showTime函数

5.数组对象:
1)数组的创建:var a=["1","krys","ok"];
 var a=new Array(); a[0]="hell0"; a[1]="world";
 var a=new Array("hello","world","welcome");
 2)数组常用的方法:
 concat()合并数组如 a=["krys"];b=["tal"];a.concat(b)=krystal;
 sort()排序数组 var a=["a","c","b"];a.sort();->a b c (默认从低到高排序)
 设置为降序:a.sort(funtion(a,b){return a-b;})
 push()在数组末尾添加一个元素var a=["a","c","b"]; a.push("d");
 reverse()翻转,对称中心点相互交换:a.reverse()= c b a ;

6.math对象
 1)常用函数
 round()四舍五入 Math.round(2.5)=3;
 random()返回0~1之间的随机数 Math.random();
 可以转换成整数:parseInt(Matn.random()*10);
 max()返回最大值
 min()返回最小值
 abs()返回绝对值

九,浏览器的内置对象BOM(browser object model)
1,window对象:大部分对象的祖先,最高级别对象之一。

1)简介:Window对象是指当前的浏览器窗口,所有的js全局变量函数以及变量都是Window对象的成员。
其中,全局变量是window对象的属性,全局函数是window对象的方法。

2)获得浏览器内部窗口的尺寸(即内容区域的尺寸,不包括滚动条工具栏等):
window.innerHeight浏览器窗口的内部高度,window.innerWidth,浏览器的内部宽度。

3)使用window.open(url)可以打开一个窗口,使用window.close()可以关闭当前窗口。

2,history对象
window.history()对象包含浏览器的历史(url)的集合
有三个方法:
1)history.back()后退,返回到前一页
2)history.forward(),前进,进入到下一页
3)history.go(),带参数,参数就是要进入的页数,-1是前一页,-2是前两页,依次类推,当前页是0.

3, timer
By using js, execute the code after a set time interval instead of executing it immediately after the function is called
There are two functions
One is setInterval() -Continuously execute the specified code at an interval of the specified number of milliseconds
One is setTimeout()-execute the specified code after pausing for the specified number of milliseconds.
You can use setTimeout to implement the function of setInterval(): just call yourself in the calling function code!
setInterval(funtion(){},1000);
setTimeout(funtion(){},1000);

You can use clearInterval(), clearTimeout() to clear this call,

4, Location object
is used to obtain the address of the current page and redirect the browser to a new page (in fact, my understanding is to parse the current address)

Properties of the Location object:
location.hostname: Returns the domain name of the web host
location.pathname: Returns the path and file name of the current page
location.port: Returns the port of the web host
location.protocol: Returns the used web protocol
location.href: Returns the url of the current page
location.assign() loads a new document, and the parameter is the path of the document to be loaded.

window.location.hostname;

5, screen object
window.screen object contains information about the user's screen
screen.avaiilWidth;//Available screen height
screen.availHeight;//Available screen width
screen.height;//Screen height
screen.width;//Screen width

6, navigation object
7, pop-up window , cookie

ten, js object-oriented thinking

Related articles:

Summary of important JavaScript knowledge points 1

Important points to note about JavaScript event "event object"_javascript skills

Related videos:

JavaScript basic strengthening video tutorial

The above is the detailed content of The most systematic summary of the key points of JavaScript (excluding basic language 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
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.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

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),

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use