如何解决识别带有click事件的子元素
我在ReactJS
中与此代码相似:
<div onClick={(e) => testeFn(e)}>
<p className="bg-primary">Test 1</p>
<p className="bg-primary">Test 2</p>
<p className="bg-primary">Test 3</p>
<p className="bg-primary">Test 4</p>
</div>
我需要单击子元素才能将其background-color
更改为红色,但是每次只有一个元素必须接收红色背景,因此,如果我单击第一个,则为“会变成红色,但是如果之后我单击第二个元素,它将收到bg红色,而第一个返回主色。
我这样做了
const testeFn = e => {
let children = e.currentTarget.children
let childrenArray = Array.from(children)
}
我的想法是遍历childrenArray
并提取每个元素,对准被点击的元素并将其bg
设置为红色,但是我不知道如何识别被点击的元素,因为循环将全部归还。也许可以使用index
,但我不知道如何。
我知道我可以使用Bootstrap内置导航,甚至可以在Google上找到一些代码,但是我真的很想学习如何做到这一点。
有什么想法吗?
解决方法
我可以想出一种解决方案,可以反转逻辑,增加一个步骤,并使用CSS设置bg
而不是Bootstrap。
我仍在遍历子元素,但不是使用循环来标识单击的元素并将其设置为选定元素,而是将所有背景设置为原始颜色(蓝色)。之后,我将点击的元素设置为背景红色。
这些步骤确保目标元素以外的所有元素都将具有bg蓝色,因为第一步将始终将所有元素设置为背景蓝色,而第二步将仅将目标元素设置为背景红色。
const testeFn = e => {
let target = e.target
let children = e.currentTarget.children
let childrenArray = Array.from(children)
childrenArray.map(child => {
child.style.backgroundColor = 'blue'
child.style.color = 'black'
})
target.style.backgroundColor = 'red'
target.style.color = 'white'
}
<div onClick={(e) => testeFn(e)}>
<p style={{backgroundColor: 'blue'}}>Test 1</p>
<p style={{backgroundColor: 'blue'}}>Test 2</p>
<p style={{backgroundColor: 'blue'}}>Test 3</p>
<p style={{backgroundColor: 'blue'}}>Test 4</p>
</div>
,
最简单的方法是使用closest()
(添加了事件侦听器以使其在此处工作)
const testeFn = e => {
let target = e.target.closest('.bg-primary');
if (target) {
// reset
document.querySelectorAll('.bg-primary').forEach(el => {
el.style.backgroundColor = 'blue';
})
// add to target
target.style.backgroundColor = 'red';
}
}
document.addEventListener('click',e => testeFn(e));
<div id="test">
<p class="bg-primary" style='background-color: blue'>Test 1</p>
<p class="bg-primary" style='background-color: blue'>Test 2</p>
<p class="bg-primary" style='background-color: blue'>Test 3</p>
<p class="bg-primary" style='background-color: blue'>Test 4</p>
</div>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。