所以我的html就像这样:
<ul id="page-nav">
<li class="text-muted menu-title">Navigation</li>
<li>
<a href="#" class="waves-effect active">
<img src="img/archive.svg" alt="archive"><span class="menu-spans"> Dashboard </span>
</a>
</li>
<li>
<a href="#" class="waves-effect">
<img src="img/speech-bubble.svg" alt="speech"><span class="menu-spans"> Chat </span>
</a>
</li>
<li>
<a href="#" class="waves-effect">
<img src="img/gains.svg" alt="speech"><span class="menu-spans"> Gains </span>
</a>
</li>
</ul>
当用户点击li中的任何元素时,我想向li添加一个类。
如何在纯JavaScript中完成?
我最初的想法如下:
document.getElementById("page-nav").addEventListener(
"click", i => {
// debug purposes
console.log(this.parentNode);
}
);
但它不起作用。
答案 0 :(得分:1)
你可以在js中使用 currentTarget 来做到这一点。我在下面添加了片段(这里我将类 .red 添加到相应的< strong> li 点击子项目时)
var k = document.getElementsByClassName("item");
for(i = 0 ;i < k.length; i++)
{
k[i].addEventListener("click",function(event){
var el = event.currentTarget;
var value = el.id;
document.getElementById(value).classList.add ("red");
});
}
&#13;
.red{
background:red;
}
&#13;
<ul id="page-nav">
<li class="text-muted menu-title">Navigation</li>
<li class="item" id="one">
<a href="#" class="waves-effect active">
<img src="img/archive.svg" alt="archive"><span class="menu-spans"> Dashboard </span>
</a>
</li>
<li class="item" id="two">
<a href="#" class="waves-effect">
<img src="img/speech-bubble.svg" alt="speech"><span class="menu-spans"> Chat </span>
</a>
</li>
<li class="item" id="three">
<a href="#" class="waves-effect">
<img src="img/gains.svg" alt="speech"><span class="menu-spans"> Gains </span>
</a>
</li>
</ul>
&#13;