[JAVAScript] [4] Use event delegation to simplify click events (including arrow functions, target)

JavaScript uses event delegation to simplify click events


当写多个点击事件时我总是会添加很多监听函数,但是利用事件委托后仅需添加父元素的监听函数,在利用冒泡就可以为每个子元素添加监听函数,大大简化了程序


foreword

The following is a switching case around event delegation (event proxy), while supplementing arrow functions and Element.target


1. Event delegation

Commonly used techniques for binding events in JavaScript, "event delegation" is to delegate the response events (click, keydown...) that originally need to be bound to the child elements to the parent element, and let the parent element take on the role of event monitoring. The principle of event proxy is the event bubbling of DOM elements.

But note: When using "event delegation", it does not mean that the closer the element to which the event is delegated to the top layer, the better. The process of event bubbling is also time-consuming. The closer to the top layer, the longer the "event propagation chain" of the event, and the more time-consuming it is. If the DOM is deeply nested, event bubbling through a large number of ancestor elements can lead to a performance penalty.

2. Arrow function

Arrow function is a function newly added by ES6 for defining function expressions.
First of all, it is explained that arrow function cannot use argument, super and new.target, nor can it be used as a constructor, and has no prototype attribute (discussed in the next section)

let arrowSum = (a,b) =>{
    
    
	return a + b;
}
//等价于
let functionExpressionSum = funtion(a,b){
    
    	
	return a + b;
}
  • If there is only one parameter, the parentheses can be omitted
let double = x =>{
    
    return 2*x}

No parameters or multiple parameters, use parentheses (x)

  • If you do not use function braces, you can perform assignment operations
let value = {
    
    };
let setName = (x) => x.name ="Matt";
setName(value);
console.log(value.name); //"Matt"
  • If you want to return an object, you need to pay special attention. If you want to return a custom object with a single expression, you will get an error if you don’t write parentheses, because there is a syntax conflict with { ... } in the function body.

Note that curly braces enclosed in parentheses are object definitions, not function bodies

x => {
    
    key: x} // 报错
x => ({
    
    key: x}) // 正确
  • The this inside the arrow function is the lexical scope, which is determined by the context. (The lexical scope is the scope defined in the lexical phase. In other words, the lexical scope is determined by where you write variables and block scopes when you write code To decide, so when the lexical analyzer processes the code, it will keep the scope unchanged)
    Supplement the lexical scope: the lexical scope rules are as follows:
    1 Only functions can limit the scope 2 Functions allow access to data in the parent scope outside the function
    3 Variable promotion rules 4 Proximity principle

三、Element.target

Compatibility

var event = e || window.event;
var tar = event.target || event.srcElement;

target和currentTarget

  • target: a specific object that triggers the event (specific to child elements).
  • currentTarget: The object of the binding event, which is always equal to this (in non-ie DOM2-level events, this points to window in ie events), and may appear in any stage of the event flow.

But in the parent-child nested relationship, the parent element is bound to the event and the child element is clicked (according to the event flow, it will be passed to the parent element without blocking the event flow, causing the event handler function of the parent element to execute) , at this time currentTarget points to the parent element, because he is the object of the binding event, and target points to the child element, because he is the specific object that triggers the event (this is the key point)

4. Examples

insert image description here
Put the four buttons in the parent element div, and use event delegation to add a click event to the parent element. The event
delegation code is as follows:

 var img = document.querySelector('.picbox img');
 var butbox = document.getElementById('butbox')
 butbox.addEventListener('click', (event) => {
    
    
            var target = event.target;
            switch (target.id) {
    
    
                case 'buttonone':
                    img.src = '../html/images/1.webp'
                    break;
                case 'buttontwo':
                    img.src = '../html/images/2.webp'
                    break;
                case 'buttonthree':
                    img.src = '../html/images/3.jpg'
                    break;
                case 'buttonfour':
                    img.src = '../html/images/4.webp'
                    break;
            }
        });

Be careful in event delegation: only read the node of the parent element

Summarize

提示:这里对文章进行总结:世界委派可以简化点击事件,箭头函数可以简化函数

Guess you like

Origin blog.csdn.net/weixin_51612770/article/details/124829894