oba*_*net 5 javascript onclick addeventlistener
按钮
我想让它与像这样的事件侦听器一起使用:
document.body.addEventListener('click', function(e) {
console.log(e.target);
if (e.target.hasAttribute('data-a-target="popout-chat-button"')) {
console.log('popout button');
}
});Run Code Online (Sandbox Code Playgroud)
<button data-a-target="popout-chat-button" data-test-selector="popout-button">Popout</button>Run Code Online (Sandbox Code Playgroud)
我无法使用 hasAttribute 检查值,最好的方法是什么。
用于e.target.getAttribute获取目标元素的属性值。然后将其与您在条件中期望的属性值进行比较if:
document.body.addEventListener('click', function(e){
console.log(e.target);
if(e.target.getAttribute('data-a-target') === "popout-chat-button"){
console.log('popout button');
}
});Run Code Online (Sandbox Code Playgroud)
<button data-a-target="popout-chat-button" data-test-selector="popout-button">Popout</button>Run Code Online (Sandbox Code Playgroud)
getAttribute() 方法返回元素的指定名称的属性值。
句法
element.getAttribute(属性名)