Event binding and event monitoring

  • Write a general event listener function

    function bindEvent(elem, type, selector, fn) {
          
          
                if (fn == null){
          
          
                    fn = selector
                    selector = null
                }
                elem.addEventListener(type, event => {
          
          
                    const target = event.target
                    if(selector) {
          
          
                        // 代理绑定
                        if (target.matches(selector)){
          
          
                            fn.call(target, event)
                        }
                    } else {
          
          
                        // 普通绑定
                        fn.call(target, event)
                    }
                })
            }
    
  • Describe the flow of event bubbling

    • Based on DOM tree structure
    • The event will bubble up along the trigger element
    • Application scenario: event agent
  • Infinite drop-down list of pictures, how to monitor the click of each picture

    • Event agent
    • Use e.target to get the trigger element
    • Use matches to determine whether to trigger the element

Guess you like

Origin blog.csdn.net/qq_39208971/article/details/109470115