js event operation syntax

Table of contents

1. Event Binding Syntax

Second, the deletion syntax of the event

1. Deletion of on syntax binding events

2. Deletion of event listening syntax

3. Default events

4. Prevent the spread of events

5. Common Event Types

1. Window-related event types

2. Mouse-related event types

3. Keyboard-related event types

4. Form related events

5. Mobile events

6. Special Events

6. Event object

7. Event delegation syntax


1. Event Binding Syntax

grammatical form 1

    Event listener label object.addEventListener('click',function(){});

grammatical form 2

    on syntax binding label object.onclick = function(){}

The on syntax is an event processing function bound by = equal to assignment. == equal to assignment essentially executes overwriting assignment, and the data assigned later will overwrite the previously stored data, that is, the event type of a label object in the on syntax can only The assignment binds an event handler. If the assignment binds multiple event handlers, the later assigned event handler will overwrite the stored event handler

Three elements of event binding

    The label object     event source is the label object that binds the event

    The 'click'          event type is the type of event bound to the label object

    function(){}     event handler is the function program executed when an event is triggered

                          It is the grammatical form of the callback function, which can be a function name or an anonymous function

Second, the deletion syntax of the event

1. Deletion of on syntax binding events

    Because the on syntax is = equal to the assignment operation, as long as a null / empty function is assigned, when the event is triggered, the executed function program will not be called to achieve the effect of deleting the event

2. Deletion of event listening syntax

    A special delete function method is required: label object.removeEventListener('event type', event handler);

    You can only delete the event handler that is bound to the function name. If the binding is an anonymous function, you cannot delete it

Notice:

    In practice, if you do not need to delete the event handler function, it is recommended to use the anonymous function syntax form

    In actual operation, if you must delete the event handler, you can only bind the function name

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div>我是div标签对象</div>
  <button>绑定</button>
  <button>删除</button>

  <script>
    //获取标签对象
    var oDiv = document.querySelector('div');
    var oBtn1 = document.querySelectorAll('button')[0];
    var oBtn2 = document.querySelectorAll('button')[1];

    oBtn1.addEventListener('click', function () {
      //on语法绑定事件
      //oDiv.onclick = function(){console.log(111)};

      //事件监听语法绑定
      //绑定的匿名函数
      oDiv.addEventListener('click', function () { console.log(111) });

      //绑定的函数名称
      oDiv.addEventListener('click', funA);
      oDiv.addEventListener('click', funB);
      oDiv.addEventListener('click', funC);

    })

    //删除绑定的事件
    oBtn2.addEventListener('click', function () {
      //删除on语法绑定的事件
      //oDiv.onclick = null;
      //oDiv.onclick = function(){};

      //绑定的匿名函数无法删除,因为两个匿名函数内存地址不同
      //假设绑定的内存地址是 00ff11
      //删除的内存地址可能是 00ffzz 
      //不能设定正确的删除的内存地址
      oDiv.removeEventListener('click', function () { console.log(111) });

      //绑定的是函数名称,函数名称中存储的是内存地址
      //以下可以删除
      oDiv.removeEventListener('click', funA);
      oDiv.removeEventListener('click', funB);
      oDiv.removeEventListener('click', funC);
    });

    function funA() {
      console.log('aaa');
    }
    function funB() {
      console.log('bbb');
    }
    function funC() {
      console.log('ccc');
    }
  </script>
</body>

</html>

3. Default events

The default event is the program effect executed by html tags by default

    There are: hyperlink click jump, form tag click jump, right mouse button

block default event

Define a formal parameter in the event processing function. The formal parameter name is generally e / event

    Label object.addEventListener('event type', function( e / event ){

           // prevent the default event from executing

           formal parameter.prevenDefault();

    })

Hyperlink

    Add click event to hyperlink label

form tag

    Add a submit event to the form tag

right click

    Add contextmenu mouse right button event to document

4. Prevent the spread of events

The same type of event is added to the parent tag and the descendant tag, and the descendant tag triggers the event. The parent tag also triggers the same type of event. This execution principle is called event propagation or bubbling event

Propagation syntax for blocking events

    Label object.addEvenListener(event type, function(e/event){

           e.stopPropagation();  

  })

How Events Propagate

There are two ways of propagating events in previous versions

    bubbling child --- parent

    capture parent --- child

Now in the new version of the browser, there is only the bubbling method and no capture method by default

    Event listener syntax binding event handler function

    Parameter 3 If set to true, the propagation execution capture method of the event

5. Common Event Types

1. Window-related event types

1.1 Browser window size monitoring event

    window.addEventListener( 'resize' ,function(){} )

1.2 Page scrolling monitoring event

    window.addEventListener( 'scrool',function(){} )

1.3 Browser loading event

    window.addEventListener( 'load',function(){})

1.5 Open url connection in a new window

    window.open(url address)

1.6 Close the current window

    window.close()

2. Mouse-related event types

  click left mouse button click

  dblclick left mouse button double click

contextmenu right mouse click

  mousedown mouse button down

  mouseup mouse button up

  mousemove mouse movement

  mouseover mouseover mouseenter

  mouseout mouse out mouseleave

3. Keyboard-related event types

   keydown keyboard key down

   keyup keyboard key up

   keypress keyboard key pressed

4. Form related events

   submit Form submission event

   The focus tag gets the focus

   The blur tab loses focus

   The change tag loses focus and the data changes

   input input data

5. Mobile events

   touchstart touch start

   touchend touch end

   touchmove touch move

6. Special Events

   transitionstart transition start

   transitionend transition end

   animationstart animation start

   animationend animation end

The event must be bound to the label of the event, that is, within the scope of the event source to trigger the event

The full screen trigger event needs to give

    document

    document.documentElement

    document.body

bind event

    Some events can be supported, some events are only supported by a certain object

6. Event object

Event object (event), the data value stored in the parameter in the event processing function, is the object that triggers the event

The object that triggers the event and the one that binds the event are not necessarily the same object

When an event is triggered, the JavaScript program automatically stores the actual parameter in the formal parameter

That is, the data information related to the tag object that triggered the event is automatically stored in the event object

Event source.addEventListener(event type, function(time object){})

       event object.target

              Stores the tag object that triggered the event

              Supports all DOM manipulation syntax

7. Event delegation syntax

Instead of directly binding events to the label object, it binds the event to the parent label, judges the different label objects that trigger the event through the event object.target, and executes different function programs

Label object.target is a DOM label object

    Tag object.target.tagName is the tag name in uppercase English characters

    Label object.target Executes DOM operations to determine what label is clicked

If there are div tags that contain span tags, h1 tags, a tags, and p tags, add different click events to each tag

Generally, each label object is obtained, the click event is bound, and the propagation of the event is prevented.

In actual operation, as long as different if judgments are triggered and different programs are executed according to different conditions, it will be OK.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div>
        我是div标签对象<br>
        <span>我是span标签</span>
        <h1 id="h1">我是h1标签</h1>
        <a href="JavaScript:;">我是a标签</a>
        <p>我是p标签</p>
    </div>

    <script>
        // 事件委托 
        // 给父级div标签添加点击事件
        // 通过 事件对象.target 判断 触发事件的是什么标签 
        // 根据不同的标签 触发执行不同的程序
        var oDiv = document.querySelector('div');

        oDiv.addEventListener('click' , function(e){
            // 事件委托 点击事件会触发 
            // 触发事件标签 标签名称是 div 证明点击的是div标签
            if( e.target.tagName === 'DIV' ){
                console.log( '您点击的是div标签' );


            }else if( e.target.tagName === 'SPAN' ){
                console.log( '您点击的是span标签' );
            
            
            }else if( e.target.id === 'h1' ){
                console.log( '您点击的是h1标签' );

            }else if( e.target.getAttribute('href') === 'JavaScript:;' ){
                console.log( '您点击的是a标签' );

            }else if( e.target.innerHTML === '我是p标签' ){
                console.log( '您点击的是p标签' );

            }
        });

    </script>
</body>
</html>

Click each tab separately, and the execution results are as follows:

Guess you like

Origin blog.csdn.net/weixin_58448088/article/details/122508058