目标是你点击的内容,所以当你点击锚点时,它是子对象,而不是锚点。不会为链上的每个元素触发该事件。
因此,您需要遍历链并检查元素。你可以用
closest()
document.addEventListener('click', function(e) {
const externalAnchor = e.target.closest('a.external-link');
if (externalAnchor) {
console.log('here');
e.preventDefault();
}
});
a {
background: blue;
color: white;
display: flex;
flex-wrap: wrap;
width: 200px;
height: 40px;
font-weight: bold;
line-height: 20px;
align-items: center;
justify-content: center;
text-align: center;
text-decoration: none;
}
a span {
display: block;
width: 100%;
font-weight: normal;
font-style: italic;
}
<a href="#" class="external-link">Click Me <span>(External)</span>