简体   繁体   English

在同一位置的多个元素上传播单击事件但没有父子关系

[英]Propagate click event on multiple elements in the same place but not have parent-child relationship

I have a question that how can I propagate a click event on 2 elements in the same place but it doesn't have parent-child relationship.我有一个问题,如何在同一个地方传播 2 个元素的点击事件,但它没有父子关系。 For example, I have this html:例如,我有这个 html:

<body>
    <button id="btn1">BUTTON 1</button>  // position fixed with top/left at 10px
    <div>
        <button id="btn2">BUTTON 2</button>  // position fixed with top/left at 10px (same place of button 1)
    </div>
</body>

So in the UI, button 1 and button 2 nearly have the same place, so I want if I click on button 2, the click event is also fired on both button 1 and button 2.所以在 UI 中,按钮 1 和按钮 2 几乎有相同的位置,所以我希望如果我点击按钮 2,点击事件也会在按钮 1 和按钮 2 上触发。

I appreciate any help.我很感激任何帮助。

You have to listen to the click event on your button 2 and then call the click event for button 1 as well.您必须在按钮 2 上监听 click 事件,然后也为按钮 1 调用 click 事件。

doesn't work if you assigned the same event to the two buttons?如果您将相同的事件分配给两个按钮,则不起作用? or is necessary the other?还是需要另一个?

function someFuntion() {/* Do something */}
button1.addEventListener('click',somefuntion)
button2.addEventListener('click',somefuntion)

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

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