Implementing jQuery's “live” binder with native Javascript

后端 未结 4 1684
不思量自难忘°
不思量自难忘° 2020-11-29 01:54

I am trying to figure out how to bind an event to dynamically created elements. I need the event to persist on the element even after it is destroyed and regenerated.

<
4条回答
  •  一生所求
    2020-11-29 02:11

    In addition to Andrew's post and Binyamin's comment, maybe this is an option:

    With this you can use 'nav .item a' as the selector. Based on Andrew's code.

    function live (eventType, elementQuerySelector, cb) {
        document.addEventListener(eventType, function (event) {
    
            var qs = document.querySelectorAll(elementQuerySelector);
    
            if (qs) {
                var el = event.target, index = -1;
                while (el && ((index = Array.prototype.indexOf.call(qs, el)) === -1)) {
                    el = el.parentElement;
                }
    
                if (index > -1) {
                    cb.call(el, event);
                }
            }
        });
    }
    
    
    
    live('click', 'nav .aap a', function(event) { console.log(event); alert('clicked'); });
    

提交回复
热议问题