Attach event to dynamic elements in javascript

前端 未结 10 2276
一生所求
一生所求 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

    var __ = function(){
        this.context  = [];
        var self = this;
        this.selector = function( _elem, _sel ){
            return _elem.querySelectorAll( _sel );
        }
              this.on = function( _event, _element, _function ){
                  this.context = self.selector( document, _element );
                  document.addEventListener( _event, function(e){
                      var elem = e.target;
                      while ( elem != null ) {
                          if( "#"+elem.id == _element || self.isClass( elem, _element ) || self.elemEqal( elem ) ){
                              _function( e, elem );
                          }
                          elem = elem.parentElement;
                      }
                  }, false );
         };
    
         this.isClass = function( _elem, _class ){
            var names = _elem.className.trim().split(" ");
            for( this.it = 0; this.it < names.length; this.it++ ){
                names[this.it] = "."+names[this.it];
            }
            return names.indexOf( _class ) != -1 ? true : false;
        };
    
        this.elemEqal = function( _elem ){
            var flg = false;
            for( this.it = 0; this.it < this.context.length;  this.it++ ){
                if( this.context[this.it] === _elem && !flg ){
                    flg = true;
                }
            }
            return flg;
        };
    
    }
    
        function _( _sel_string ){
            var new_selc = new __( _sel_string );
            return new_selc;
        }
    

    Now you can register event like,

    _( document ).on( "click", "#brnPrepend", function( _event, _element ){
          console.log( _event );
          console.log( _element );
          // Todo
    
      });
    

    Browser Support

    chrome - 4.0, Edge - 9.0, Firefox - 3.5 Safari - 3.2, Opera - 10.0 and above

提交回复
热议问题