繁体   English   中英

使用点击事件识别子元素

[英]Identify a child element with a click event

我在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 red 并且第一个元素会返回到主元素。

我这样做了:

const testeFn = e => {

    let children = e.currentTarget.children

    let childrenArray = Array.from(children)
}

我的想法是遍历childrenArray并提取每个元素,瞄准单击的元素并将其bg设置为红色,但我不知道如何识别单击的元素,因为循环将返回所有元素。 也许有了index就有可能,但我不知道怎么做。

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

有任何想法吗?

我可以想出一个反转逻辑的解决方案,添加一个步骤并使用 css 来设置bg而不是 Bootstrap。

我仍在循环子元素,但不是使用循环来识别单击的元素并将其设置为选定的元素,而是将所有背景设置为原始颜色,即蓝色。 之后,我将单击的元素设置为背景为红色。

这些步骤确保除了目标元素之外的所有元素都具有蓝色背景,因为第一步将始终将所有元素设置为背景蓝色,而第二步将仅将目标元素设置为背景红色。

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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM