原生js添加html添加class点击的n种实现方法

内容参考: stackoverflow:JavaScript click event listener on class?

方法1:

通过选择器获取,然后添加时间

//1. 通过选择器获取class,任意
let x = document.querySelectorAll(".vdr-stick");
//旧的浏览器不识别`getElementsByClassName`,因此可能返回`undefined`. 如:IE6, IE7, IE8
let x = document.getElementsByClassName(".vdr-stick");

//2. 遍历
for (let item of x) {
    item.onclick = function clickHandler(event) {
        event.stopPropagation();
    };
}
//若支持es6,也可以按如下方式循环
Array.from(classname).forEach(function(element) {
    element.addEventListener('click', myFunction);
});

此外注意:

getElementsByClassName doesnt return an array, but a HTMLCollection in most, or a NodeList is some browsers (Mozilla ref). Both of these types are Array-Like, (meaning that they have a length property and the objects can be accessed via their index), but are not strictly an Array or inherited from an Array. (meaning other methods that can be performed on an Array cannot be performed on these types)

方法2:

可以监听子元素

//举例1
var base = document.querySelector('#base'); // the container for the variable content
var selector = '.card'; // any css selector for children

base.addEventListener('click', function(event) {
  // find the closest parent of the event target that
  // matches the selector
  var closest = event.target.closest(selector);
  if (closest && base.contains(closest)) {
    // handle class event
  }
});

//举例2
document.body.addEventListener('click', function (evt) {
    if (evt.target.className === 'databox') {
        alert(this)
    }
}, false);