JavaScript knowledge points-week 5.md

1. Anonymous function

1. Functions learned

Functions learned grammar
Ordinary function function function name(){}
Event handler onclick = function(){}
Constructor function Tab(){}
Expression function var variable name = function(){}
Anonymous function function (){ // code block}
   //匿名函数
   function (){
    
    

       console.log(123);

   }

2. Execute the function immediately

  1. Immediately execute function: immediately invoked function expression self-executing function

  2. Advantages: Avoid global variable pollution and reduce unnecessary memory waste

   (function (){
    
    

       console.log(1);

   })();

   
   (function (){
    
    

       console.log(2);

   }());

   
   // 2. 有参数: 形参: 函数声明后的括号中    实参: 函数调用的括号中

   (function (a, b){
    
    

       console.log(a, b);

   }(10,20));

   
   // 3. 有返回值: return 值

   var s = (function (a, b){
    
    

       console.log(a, b);

       return a + b;

   }(10,20));

   console.log(s);

Two, closure

1. The concept of closure

Functions that can read the internal variables of other functions (set functions in the function, internal functions access the variables of the external function), in essence, a bridge that connects the inside and outside of the function

2. Features of closure:

The variable used in the closure is stored in memory, similar to global variables, to avoid global pollution

   // 1. 闭包:

   function fn(){
    
    

       var s = 10;

       return function(){
    
    

           console.log(s++);

       }

   }

   // var f = fn(); 

   // console.log(f); // function(){ console.log(s++); }

   // f(); // 10

   // f(); // 11

   // f(); // 12

   // console.log(s); // 全局s 没有

   
   fn()(); // 10

   fn()(); // 10

   fn()(); // 10

2. Closure function

  • 1 —Resolve the impact of global variable i
   var li = document.getElementsByTagName('li');

   console.log(li);

   // for循环执行太快, i最后保留在结束条件

   // 解决全局变量i带来的影响

   for (var i = 0; i < li.length; i++) {
    
    

       (function (s) {
    
    

           li[s].onclick = function () {
    
    

               alert(s); // 5

           }

       })(i);

   }
  • 2 — Simulate private variables
   function myName(v){
    
    

       var val = v;

       return {
    
    

           'sayName': function(){
    
    

               console.log(val);

           },

           'setName': function(n){
    
    

               val = n;

           }

       }

   }    

   var s = myName('付小朋友');

   console.log(s);

   s.sayName();

   s.setName('付大朋友');

   s.sayName();

Three, ajax

1. Ajax concept

Asynchronous javascript and xml (asynchronous js and xml) is a web development technology for creating interactive web applications. It can quickly create dynamic web pages. It is through a small amount of data interaction with the background, ajax can achieve asynchronous updates of web pages .

2. Synchronous/asynchronous

  • Synchronization: When the client and the server are interacting data, they can't do other things

  • Asynchronous: When the client and the server exchange data, they can do other things

3. ReadyState: 5 types

readyState Returns the current status of the XMLHTTP request
0 Object created
1 Established a connection
2 Sent the request
3 Received this request, and started processing, it has not been processed yet
4 The processing has been completed, and the response packet is returned

4. Status: network status code

Description of each network status code
http status code

category Reason phrase
1xx Informational status code The server is processing the request
2xx Request succeeded The request is processed normally
3xx Request redirection Need to perform additional operations to complete the request
4xx Client error There was an error in the client request and the server could not process the request
5xx Server Error Server processing request error
  • Common status codes are descriptions
status code description
200 OK The request sent by the client to the server is processed normally and returned
201 Created Request has been fulfilled
202 Accepted The server has accepted the request, but has not yet processed it
204 No Content The server successfully processed the request, but does not need to return any entity content (there is no resource to return)
301 Moved Permanently Permanent redirect, indicating that the requested resource is assigned a new URL, and the changed URL should be used later
302 Found Temporary redirect, indicating that the requested resource has been assigned a new URL, and it is hoped that the new URL will be used for this visit
303 See Other Indicates that the requested resource is assigned a new URL, and the GET method should be used to obtain the requested resource.
400 Bad Request There is a syntax error in the request message
401 Unauthorized Without permission, HTTP authentication is required
403 Forbidden The server denied the access (the access rights have problems)
404 Not Found Indicates that the requested resource cannot be found on the server. In addition, it can also be used when the server rejects the request but does not want to give the reason for the rejection
405 Method Not Allowed Wrong opening method (resources are forbidden)
500 Internal Server Error An error occurred while the server was executing the request. It may also be a bug in the web application or some temporary error
503 Server Unavailable The server is temporarily overloaded or is down for maintenance, unable to process the request

5. The process of ajax creation

  1. get request

    1. Create ajax request object

    2. Establish a connection ajax.open (request method, request address + data, whether it is asynchronous);

    3. Send request ajax.send();

    4. Monitor processing situation

   // 1. 创建ajax请求对象

   var ajax = new XMLHttpRequest(); // http: 超文本传输协议  request:请求

   // var ajax = new ActiveXObject('Microsoft.XMLHTTP'); // ie6创建

         
   // 2. 建立连接 ajax.open(请求方式, 请求地址+data, 是否异步);

   // 请求方式: get、post

   // 请求地址+data: 访问的地址及传输的数据, 请求地址?key=value&key=value

   // 是否异步: 布尔值, true---异步   false---同步

   ajax.open('get', 'a.txt?a=1&b=2', true);

   // 3. 发送请求 ajax.send();

   ajax.send();
       
   // 4. 监听处理情况

   ajax.onreadystatechange = function(){
    
    

             if(ajax.readyState == 4){
    
    // 请求处理完成

                 if(ajax.status == 200){
    
     // 请求成功

                     console.log(ajax.response);

                 }

             }

   }
  1. post request

    1. Create ajax request object

    2. Establish a connection ajax.open (request method, request address, whether it is asynchronous);

    3. Set request header\coding format: tell the server the type of data currently submitted

    4. Send request ajax.send(key=value&key=value);

    5. Monitor processing situation

   // 1. 创建ajax请求对象

   var ajax = new XMLHttpRequest(); // http: 超文本传输协议 request:请求

         

   // 2. 建立连接 ajax.open(请求方式, 请求地址, 是否异步);

   // 请求方式: get、post

   // 请求地址: 访问的地址及传输的数据, 请求地址

   // 是否异步: 布尔值, true---异步   false---同步

   ajax.open('post', 'a.txt', true);

         

   // 2.1 设置请求头\编码格式:告诉服务器当前提交数据的类型

   ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=utf-8');

        

   // 3. 发送请求 ajax.send(key=value&key=value);

   ajax.send('a=1&b=2');

        
   // 4. 监听处理情况

   ajax.onreadystatechange = function(){
    
    

         if(ajax.readyState == 4){
    
    // 请求处理完成

             if(ajax.status == 200){
    
     // 请求成功

                 console.log(ajax.response);

             }

         }
   }
  1. Content-type parameter
  • application/x-www-form-urlencoded: default, form

  • text/plain: text

  • multiple/form-data: upload file

Four, json

1. json format data

  • 1.json文件后缀: .json

  • 2.文件中2种数据格式: []{}

  • 3.key:value,key必须加双引号

  • 4.value只能是简单数据类型: string\number\boolean\null{}[] 函数、undefined、变量不能用

  • 5.string必须要加双引号

2、json数据转成js数据

  • js: {}默认就是完整的js代码块

  • 方法一:eval(要转的数据)

  • 方法二:JSON.parse(要转的数据)

   myjsKu.ajax({
    
    

          'url': 'student.json', //相对html页面的地址

          'success': function(res) {
    
    

                console.log(res); //string类型

                //js中 {}默认就是完整的js代码块

                //方法一:eval(要转的数据),将字符串转成js代码并执行其中的js代码

                // var r = eval(res);//res是字符串--转成表达式加() 

                var r = eval('(' + res + ')'); //运行字符串中js的代码

                console.log(r);

                console.log(eval('3+2')); //5

                //方法二、JSON.parse(要转的数据):json数据转成js数据

                console.log(JSON.parse(res));

                var r = JSON.parse(res);

                //字符串转成数组后对其进行遍历--获取到每一个学生的信息

                //ajax请求后操作数组的方式

                for (var i = 0; i < r.length; i++) {
    
    

                    console.log(r[i]);

                    ul.innerHTML += '<li><span>' + r[i].name + '</span>&nbsp;&nbsp;<span>' + r[i].sex + '</span>&nbsp;&nbsp;&nbsp;&nbsp;<span>' + r[i].age + '</span></li>'

                }

          }
    })

五、移动端事件

  1. touchstart: 当手指在屏幕上按下的时候

  2. touchmove: 当手指在屏幕上移动的时候

  3. touchend: 当手指离开屏幕的时候触发

   div.ontouchstart = function(){
    
    

       console.log('这是点击touch');

   }

   div.addEventListener('touchmove', function(){
    
    

       console.log('touchmove');

   });

   div.addEventListener('touchend', function(){
    
    

       console.log('touchend');

   });

   // 注意: 在移动端一般使用事件绑定的方式添加事件
  1. pc端事件在移动端中的问题: 有一个300ms的延迟

  2. 移动端事件问题:

    1. 点透: 当两个元素叠加在一起,并且下方元素有点击事件或连接跳转时, 当上方元素点击隐藏后,并且点击事件时间不超过300ms, 事件会漂移到下方元素上, 造成了点透事件
    2. 解决
      • 阻止默认事件,在 touch 时间的某个阶段执行 event.preventDefault() ,去取消系统生成的 click 事件,一半在 touchend 中执行
      • 要消失的元素延时300ms,然后在消失
   var div = document.getElementsByTagName('div')[0];

   div.addEventListener('touchstart', function(){
    
    

          div.style.display = 'none';

   });
  1. 事件对象
  • 事件处理函数的第一个参数
   div.addEventListener('touchstart', function(ev){
    
    

   console.log(ev); // TouchEvent

   console.log(ev.touches); // 当前位于整个屏幕上的手指列表

   console.log(ev.targetTouches); // 当前位于目标元素上的一个手指列表

   console.log(ev.changedTouches); // 当前事件的手指列表

      
   var touch = ev.changedTouches[0]; // 在事件的手指列表中拿出来第一个手指

   console.log(touch);

   console.log(touch.identifier); // 标识符

   console.log(touch.target); // 目标源

   console.log(touch.screenX, touch.screenY); // 显示器

   console.log(touch.clientX, touch.clientY); // 到可视区域的左上角

   console.log(touch.pageX, touch.pageY); // 到页面左上角的距离

   console.log(touch.radiusX, touch.radiusY); // 手指触发的圆的半径

   console.log(touch.force); // 压力的大小

   console.log(touch.rotationAngle); // 旋转角度

   });

六、touch.js

  1. 介绍: 移动端的手势识别和事件库, 百度clouda团队维护, 在百度内部也是广泛应用的

  2. 搜索: touch.js: touch cdn —> bootcdn 0.2.14

  3. touch.js: 标准格式版本, 学习

    touch.min.js: 压缩版本, 工作

  4. 作用: 专门为移动设备设计, 请在webkit内核中使用

  5. touch.on()

    1. touch.on(elem, type, callback);

      ​ elem: 要绑定事件的对象

      ​ type: 事件类型

      ​ callback: 回调函数

      • 给一个元素绑定一个事件

      • 给一个元素的同一事件添加不同的处理函数

      • 给一个元素不同事件添加同一处理函数

      • 给同一元素不同事件添加不同处理函数

   var div = document.getElementsByTagName('div')[0];

   // 1. 给一个元素绑定一个事件

   // tap: 单击

   touch.on(div, 'tap', function (ev) {
    
    

            console.log(ev.type);

   });

   function callB(ev){
    
    

            console.log('当前事件类型是: ' + ev.type);

    }

   // 2. 给一个元素的同一事件添加不同的处理函数

   touch.on(div, 'tap', callB);

        

   // 3. 给一个元素不同事件添加同一处理函数

   // hold: 长按  doubletap:双击事件

   touch.on(div, 'tap hold doubletap', callB);

        

   // 4. 给同一元素不同事件添加不同处理函数

   // touch.on(elem, {'事件类型': 事件处理函数});

   touch.on(div, {
    
    

            'hold': function(){
    
    

                console.log('1');

            },

            'tap': function(){
    
    

                console.log(2);

            }

   });
  1. 事件委托:touch.on(父元素, type, selector, callback)

    父元素:父元素\选择器

    type: 事件类型

    selector: 子元素的选择器

    callback: 回调函数

   var div = document.getElementsByTagName('div')[0];

   touch.on(div, 'tap', 'span.box,em', function(ev){
    
    

          console.log(ev.target);

          console.log(this);

   });
  1. 事件对象
   console.log(ev);

   console.log(ev.originEvent); // 原生的事件对象

   console.log(ev.type); // 事件类型

   console.log(ev.rotation); // 旋转角度

   console.log(ev.scale); // 缩放比例

   console.log(ev.direction); // 操作方向

   console.log(ev.position); // 位置信息

   console.log(ev.distanceX, ev.distanceY); // 手势事件中滑动事件在横线和纵向上的偏移量, 以当前点击开始的位置作为坐标原点,分成四象限, 向上、左是负值, 向下、右是正值

   console.log(ev.angle); // rotate事件触发的时候, 旋转的角度

   console.log(ev.duration, '1----'); // 时长(touchstart到touchend)
事件 描述
缩放类 pinchstart 缩放手势起点
pinchend 缩放手势终点
pinch 缩放手势
pinchin 收缩
pinchout 放大
旋转类 rotateleft 向左旋转
rotateright 向右旋转
rotate 旋转
滑动类 swipestart 滑动手势起点
swiping 滑动中
swipeend 滑动手势终点
swipeleft 向左滑动
swiperight 向右滑动
swipeup 向上滑动
swipedown 向下滑动
swipe 滑动
拖动类 dragstart 拖动开始
drag 拖动
dragend 拖动结束
长按 hold
单击、双击 Tap、doubletap

Guess you like

Origin blog.csdn.net/qq_41008567/article/details/108965025