I have some <a>
tags which are dynamically created and inside the <a>
tags I have added Font Awesome Icons. So the HTML looks like this:
<ul>
<li><a><i class="fa fa-check" aria-hidden="true"></i></a> One</li>
<li><a><i class="fa fa-check" aria-hidden="true"></i></a> Two</li>
</ul>
So now I want to toggle a class when clicking on the <a>
tags. Since they are live elements, I have to add Event Listener to <body>
or the parent element. But event.target
is always showing the <i>
tag whenever I click on the <a>
tag. And this gives me trouble and I have to write a lot more code to select the <a>
tag. I think this makes my code messy and isn't a proper way.
How can I solve the problem?
答案 0 :(得分:1)
event.target
返回树中最深的元素。由于<i>
在<a>
内部,因此将其作为当前目标返回。要解决此问题,您可以使用Element.closest()
进入适当的元素。
document.body.addEventListener("click", (event) => {
const aEl = event.target.closest("a");
if (aEl) {
aEl.classList.toggle("active")
}
})
a {
color: brown;
}
.active {
color: mediumseagreen;
}
<link href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" rel="stylesheet"/>
<ul>
<li><a><i class="fa fa-check" aria-hidden="true"></i></a> One</li>
<li><a><i class="fa fa-check" aria-hidden="true"></i></a> Two</li>
</ul>
答案 1 :(得分:0)
我通常为此使用Jquery
$("body").on('click','a tag selector',function(){
console.log('clicked')
});
更新1
香草:
document.addEventListener('click',function(e){
if(e.target && e.target.id== 'id of a tag'){
console.log('clicked') ;
}
})
有关详细信息搜索:DOM事件委托
答案 2 :(得分:0)
我认为这会有所帮助
//Keep This In A Function And Attach It To A Onclick() Method
document.addEventListener("here_goes_the_id", function(){
// The Things You Want To Do Go Here
});