Emulate jQuery “on” with selector in pure javascript

前端 未结 3 1521
时光取名叫无心
时光取名叫无心 2020-12-05 19:39

I would emulate in pure javascript the main functionality of jQuery .on( events , selector , data) method.

For example

$(document).on(\'click\',\'.         


        
3条回答
  •  忘掉有多难
    2020-12-05 20:33

    Update for 2017: current DOM standards like closest mean this is now much easier.

    const addEventForChild = function(parent, eventName, childSelector, cb){      
      parent.addEventListener(eventName, function(event){
        const clickedElement = event.target,
        matchingChild = clickedElement.closest(childSelector)
        if (matchingChild) cb(matchingChild)
      })
    };
    

    To use it just:

    addEventForChild(parent, 'click', '.child', function(childElement){
      console.log('Woo click!', childElement)
    })
    

    Here's a jsfiddle

提交回复
热议问题