原生js添加html添加class点击的n种实现方法
内容参考: stackoverflow:JavaScript click event listener on class?
方法1:
通过选择器获取,然后添加时间
let x = document.querySelectorAll(".vdr-stick");
let x = document.getElementsByClassName(".vdr-stick");
for (let item of x) {
item.onclick = function clickHandler(event) {
event.stopPropagation();
};
}
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:
可以监听子元素
var base = document.querySelector('#base');
var selector = '.card';
base.addEventListener('click', function(event) {
var closest = event.target.closest(selector);
if (closest && base.contains(closest)) {
}
});
document.body.addEventListener('click', function (evt) {
if (evt.target.className === 'databox') {
alert(this)
}
}, false);