简体   繁体   English

是否可以将内部Div Click绑定到外部Div?

[英]Is it possible to bind inner Div Click to Outer Div?

I am trying to trigger a Function whenever I click on a Div, but that Div has an inner Div which means that If I click inside it it will trigger the onClick but on the wrong Div 我试图在每次单击Div时触发一个功能,但是该Div有一个内部Div,这意味着如果我在内部单击,它将触发onClick但在错误的Div上

I've looked around on Internet but couldn't find any answers. 我在Internet上四处张望,但找不到任何答案。

A map function that returns the code below 一个返回下面代码的map函数

<Card onClick={props.setSelectedTemplate}  key={template.id} className="AdCopies" id={template.id.toString()}>
        <SimpleAdCopy headlines={template.headlines} descriptions={template.descriptions} url={'www.google.com'}/>
 </Card>

function handleClick(event) {
    console.log(event.target.id)
  }

I need the click to be always bounded to the outer div even if I click on the inner Div 即使单击内部Div,我也需要始终将单击限制在外部div上

You want to use event.currentTarget instead of event.target . 您要使用event.currentTarget而不是event.target target is what was clicked, currentTarget is the element the event was bound to. target是单击的对象, currentTarget是事件绑定到的元素。

As far as I understood it is about the React, isn't it? 据我了解,这是关于React的,不是吗? Anyway if you want to stop event bubbling ( https://www.sitepoint.com/event-bubbling-javascript/ ) you should add onClick handler to the inner div and inside a callback do something like this 无论如何,如果您想停止事件冒泡( https://www.sitepoint.com/event-bubbling-javascript/ ),则应在内部div中添加onClick处理程序,并在回调内部执行以下操作

<SimpleAdCopy onClick= {event => event.stopPropagation()} />

It stops event bubbling and lets you avoid onClick invocation on outer div 它停止事件冒泡,并让您避免在外部div上进行onClick调用

About stop propagation: https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation 关于停止传播: https : //developer.mozilla.org/zh-CN/docs/Web/API/Event/stopPropagation

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

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