Javascript 使用单击事件标识子元素

Javascript 使用单击事件标识子元素,javascript,html,css,reactjs,dom,Javascript,Html,Css,Reactjs,Dom,我在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>

我在
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>
我的想法是循环
childrenArray
并提取每个元素,将单击的元素瞄准并将其
bg
设置为红色,但我不知道如何识别单击的元素,因为循环将返回所有元素。也许有了
索引
这是可能的,但我不知道怎么做

我知道我可以使用Bootstrap内置导航,甚至可以在Google上找到一些代码,但我真的很想学习如何做到这一点


有什么想法吗?

最简单的方法是使用
最近的()

const testeFn=e=>{
设target=e.target.closest('.bg primary');
如果(目标){
//重置
document.querySelectorAll('.bg primary').forEach(el=>{
el.style.backgroundColor='蓝色';
})
//添加到目标
target.style.backgroundColor='red';
}
}
document.addEventListener('click',e=>testeFn(e))

测试1

测试2

测试3

测试4


我可以想出一个解决方案来反转逻辑,添加一个步骤,并使用css设置
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>
这些步骤确保除目标元素外,所有元素均为背景蓝色,因为第一步始终将所有元素设置为背景蓝色,第二步仅将目标元素设置为背景红色

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>
const testeFn=e=>{
让target=e.target
让children=e.currentTarget.children
让childrenArray=Array.from(子对象)
childrenArray.map(child=>{
child.style.backgroundColor='blue'
child.style.color='black'
})
target.style.backgroundColor='red'
target.style.color='white'
}
测试fn(e)}>

测试1

测试2

测试3

测试4


您的答案可能有效,但我明确表示我正在使用React,您编辑了代码并给了我一个html答案。该函数仍然适用于React。。。你应该能够提取逻辑,对吗?您只需要在onClick={}中调用它