将click事件添加到javascript插入的元素中

时间:2017-07-31 14:01:06

标签: javascript event-delegation

如果我点击第一个"编辑"我得到console.log('click happend')但是如果我通过javascript添加其中一个框(点击"添加框")然后从这个新框中编辑click不起作用。我知道这是因为当元素不存在时javascript运行,这就是没有点击事件监听器的原因。我也知道jQuery我可以这样做:

$('body').on('click', '.edit', function(){ // do whatever };

那会起作用。

但是如何使用简单的Javascript进行此操作?我无法找到任何有用的资源。创建了一个我想要工作的简单示例。解决这个问题的最佳方法是什么?

所以问题是:如果你添加一个框然后点击"编辑"没有任何反应。



var XXX = {};
XXX.ClickMe = function(element){
    this.element = element;
    
    onClick = function() {
        console.log('click happend');
    };
    
    this.element.addEventListener('click', onClick.bind(this));
};

[...document.querySelectorAll('.edit')].forEach(
    function (element, index) {
        new XXX.ClickMe(element);
    }
);


XXX.PrototypeTemplate = function(element) {
    this.element = element;
    var tmpl = this.element.getAttribute('data-prototype');

    addBox = function() {
        this.element.insertAdjacentHTML('beforebegin', tmpl);
    };

    this.element.addEventListener('click', addBox.bind(this));
};


[...document.querySelectorAll('[data-prototype]')].forEach(
    function (element, index) {
        new XXX.PrototypeTemplate(element);
    }
);

[data-prototype] {
  cursor: pointer;
}

<div class="box"><a class="edit" href="#">Edit</a></div>

<span data-prototype="<div class=&quot;box&quot;><a class=&quot;edit&quot; href=&quot;#&quot;>Edit</a></div>">Add box</span>
&#13;
&#13;
&#13;

JSFiddle here

This Q/A is useful information但它没有回答我关于如何解决问题的问题。就像我如何为那些动态插入DOM的元素调用像new XXX.ClickMe(element);这样的eventListener一样?

4 个答案:

答案 0 :(得分:2)

你可以这样做......

document.addEventListener('click',function(e){
    if(e.target && e.target.className.split(" ")[0]== 'edit'){
     new XXX.ClickMe(e.target);}
 })

&#13;
&#13;
var XXX = {};
XXX.ClickMe = function(element) {
  this.element = element;


  this.element.addEventListener('click', onClick.bind(this));
};



XXX.PrototypeTemplate = function(element) {
  this.element = element;
  var tmpl = this.element.getAttribute('data-prototype');

  addBox = function() {
    this.element.insertAdjacentHTML('beforebegin', tmpl);
  };

  this.element.addEventListener('click', addBox.bind(this));
};


[...document.querySelectorAll('[data-prototype]')].forEach(
  function(element, index) {
    new XXX.PrototypeTemplate(element);
  }
);


document.addEventListener('click', function(e) {
  if (e.target && e.target.className.split(" ")[0] == 'edit') {
    console.log('click happend');
  }
})
&#13;
[data-prototype] {
  cursor: pointer;
}
&#13;
<div class="box"><a class="edit" href="#">Edit</a></div>

<span data-prototype="<div class=&quot;box&quot;><a class=&quot;edit&quot; href=&quot;#&quot;>Edit</a></div>">Add box</span>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

像jQuery一样:拥有一个控制事件委托的父元素。在下文中,我使用document.body作为父级:

document.body.addEventListener('click', e => {
  if (e.target.matches('.edit')) {
    // do whatever 
  }
});

工作示例:

var XXX = {};
XXX.PrototypeTemplate = function(element) {
  this.element = element;
  var tmpl = this.element.getAttribute('data-prototype');
  addBox = function() {
    this.element.insertAdjacentHTML('beforebegin', tmpl);
  };
  this.element.addEventListener('click', addBox.bind(this));
};


new XXX.PrototypeTemplate(document.querySelector('[data-prototype]'));

document.body.addEventListener('click', e => {
  if (e.target.matches('.edit')) {
    // do whatever
    console.log('click happend');
  }
});
[data-prototype] {
  cursor: pointer;
}
<div class="box"><a class="edit" href="#">Edit</a></div>
<span data-prototype="<div class=&quot;box&quot;><a class=&quot;edit&quot; href=&quot;#&quot;>Edit</a></div>">Add box</span>

了解MDN对Element.prototype.matches所说的内容。

答案 2 :(得分:2)

这是一种模仿$('body').on('click', '.edit', function () { ... })的方法:

document.body.addEventListener('click', function (event) {
  if (event.target.classList.contains('edit')) {
    ...
  }
})

在你的例子中使用它(我将稍微修改一下):

var XXX = {
  refs: new WeakMap(),
  ClickMe: class {
    static get (element) {
      // if no instance created
      if (!XXX.refs.has(element)) {
        console.log('created instance')
        // create instance
        XXX.refs.set(element, new XXX.ClickMe(element))
      } else {
        console.log('using cached instance')
      }
      
      // return weakly referenced instance
      return XXX.refs.get(element)
    }

    constructor (element) {
      this.element = element
    }
    
    onClick (event) {
      console.log('click happened')
    }
  },
  PrototypeTemplate: class {
    constructor (element) {
      this.element = element
      
      var templateSelector = this.element.getAttribute('data-template')
      var templateElement = document.querySelector(templateSelector)
      // use .content.clone() to access copy fragment inside of <template>
      // using template API properly, but .innerHTML would be more compatible
      this.template = templateElement.innerHTML
      
      this.element.addEventListener('click', this.addBox.bind(this))
    }
    
    addBox () {
      this.element.insertAdjacentHTML('beforeBegin', this.template, this.element)
    }
  }
}

Array.from(document.querySelectorAll('[data-template]')).forEach(function (element) {
  // just insert the first one here
  new XXX.PrototypeTemplate(element).addBox()
})

// event delegation instead of individual ClickMe() event listeners
document.body.addEventListener('click', function (event) {
  if (event.target.classList.contains('edit')) {
    console.log('delegated click')
    // get ClickMe() instance for element, and create one if necessary
    // then call its onClick() method using delegation
    XXX.ClickMe.get(event.target).onClick(event)
  }
})
[data-template] {
  cursor: pointer;
}

/* compatibility */
template {
  display: none;
}
<span data-template="#box-template">Add box</span>

<template id="box-template">
  <div class="box">
    <a class="edit" href="#">Edit</a>
  </div>
</template>

这使用WeakMap()来保存对ClickMe()的每个实例的弱引用,这允许事件委派通过仅为每个.edit元素初始化一个实例来有效地委派,然后引用已经通过静态方法ClickMe.get(element)对未来的委派点击创建了实例。

弱引用允许ClickMe()的实例被垃圾收集,如果它的元素键从DOM中删除并超出范围。

答案 3 :(得分:0)

感谢所有人回答这个问题,这些都是有用的信息。以下是什么:

包装XXX.InitializeAllFunctions = function(wrap) {}内所需的所有功能,并将document作为第一页加载的包装传递。所以它的行为就像以前一样。插入新DOM元素时,只需将这些元素传递给此函数,然后再插入DOM。像魅力一样:

var XXX = {};

XXX.ClickMe = function(element){
    this.element = element;
    onClick = function() {
        console.log('click happend');
    };
    this.element.addEventListener('click', onClick.bind(this));
};

XXX.PrototypeTemplate = function(element) {
    this.element = element;

    addBox = function() {
        var tmpl = this.element.getAttribute('data-prototype');
        var html = new DOMParser().parseFromString(tmpl, 'text/html');

        XXX.InitializeAllFunctions(html);  // Initialize here on all new HTML
                                           // before inserting into DOM

        this.element.parentNode.insertBefore(
            html.body.childNodes[0],
            this.element
        );
    };

    this.element.addEventListener('click', addBox.bind(this));
};

XXX.InitializeAllFunctions = function(wrap) {

    var wrap = wrap == null ? document : wrap;

    [...wrap.querySelectorAll('[data-prototype]')].forEach(
        function (element, index) {
            new XXX.PrototypeTemplate(element);
        }
    );

    [...wrap.querySelectorAll('.edit')].forEach(
        function (element, index) {
            new XXX.ClickMe(element);
        }
    );
};

XXX.InitializeAllFunctions(document);
[data-prototype] {
  cursor: pointer;
}
<div class="box"><a class="edit" href="#">Edit</a></div>
<span data-prototype="<div class=&quot;box&quot;><a class=&quot;edit&quot; href=&quot;#&quot;>Edit</a></div>">Add box</span>