Attach event to dynamic elements in javascript

前端 未结 10 2256
一生所求
一生所求 2020-11-21 23:16

I\'m trying to insert html data dynamically to a list that is dynamically created, but when i try to attach an onclick event for the button that is dynamically created the e

10条回答
  •  爱一瞬间的悲伤
    2020-11-21 23:35

    I've made a simple function for this.

    The _case function allows you to not only get the target, but also get the parent element where you bind the event on.

    The callback function returns the event which holds the target (evt.target) and the parent element matching the selector (this). Here you can do the stuff you need after the element is clicked.

    I've not yet decided which is better, the if-else or the switch

    var _case = function(evt, selector, cb) {
      var _this = evt.target.closest(selector);
      if (_this && _this.nodeType) {
        cb.call(_this, evt);
        return true;
      } else { return false; }
    }
    
    document.getElementById('ifelse').addEventListener('click', function(evt) {
      if (_case(evt, '.parent1', function(evt) {
          console.log('1: ', this, evt.target);
        })) return false;
    
      if (_case(evt, '.parent2', function(evt) {
          console.log('2: ', this, evt.target);
        })) return false;
    
      console.log('ifelse: ', this);
    })
    
    
    document.getElementById('switch').addEventListener('click', function(evt) {
      switch (true) {
        case _case(evt, '.parent3', function(evt) {
          console.log('3: ', this, evt.target);
        }): break;
        case _case(evt, '.parent4', function(evt) {
          console.log('4: ', this, evt.target);
        }): break;
        default:
          console.log('switch: ', this);
          break;
      }
    })
    #ifelse {
      background: red;
      height: 100px;
    }
    #switch {
      background: yellow;
      height: 100px;
    }
    Click me 1!
    Click me 2!
    Click me 3!
    Click me 4!

    Hope it helps!

提交回复
热议问题