在下面的代码中,我有四个元素。单击特定元素后,我希望它更改颜色。现在,由于某种原因,整行元素都在改变颜色,而不是单个元素。这是我的代码:
<style>
.tag14 span {
padding: 6px 10px;
background: brown;
border-radius: 20px;
color: #091747;
font-family: Roboto;
font-size: 14px;
margin: 0 4px 8px 0;
font-weight: 500;
display: inline-block;
word-wrap: break-word;
white-space: normal;
cursor: pointer;
}
}
.tag14 span:focus{
background:green;
}
</style>
<script>
function myfunction(elmt)
{
elmt.style.backgroundColor = "blue";
}
</script>
<div class="tag14" onclick="myfunction(this);">
<span class="tag_span">
Hello
</span>
<span class="tag_span">
Hi
</span>
<span class="tag_span">
Hello
</span>
<span class="tag_span">
Hi
</span>
<span class="tag_span">
Hello
</span>
</div>
我怀疑这与类的命名方式以及onclick函数的参数有关。
on*
像希望使用内联style
属性那样使用内联处理程序。JavaScript应该只放在一个地方-那就是您的script
。myfunction
-因为它对任何人都没有任何意义。确切地将函数命名为函数的简短描述或返回的值。const addActiveClass = (evt) => {
evt.currentTarget.classList.add("is-active")
};
const getUserData = (evt) => {
const user_id = evt.currentTarget.dataset.userId;
console.log(`get data of user ID: ${user_id} from DB`);
};
const EL_tag_children = document.querySelectorAll(".tag span");
EL_tag_children.forEach(EL => {
EL.addEventListener("click", addActiveClass)
EL.addEventListener("click", getUserData)
});
.tag span {
padding: 6px 10px;
background: brown;
border-radius: 20px;
color: #091747;
font-family: Roboto;
font-size: 14px;
margin: 0 4px 8px 0;
font-weight: 500;
display: inline-block;
word-wrap: break-word;
white-space: normal;
cursor: pointer;
}
.tag span.is-active {
background-color: blue;
}
<div class="tag">
<span data-user-id="23">John</span>
<span data-user-id="566">Amanda</span>
<span data-user-id="101">Fredrick</span>
<span data-user-id="42">Paulina</span>
<span data-user-id="50">Jaqueline</span>
</div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句