如何防止JavaScript中的事件冒泡 [英] How to prevent event bubbling in javascript

查看:52
本文介绍了如何防止JavaScript中的事件冒泡的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

感谢您的阅读...我会直接解决这个问题的.

thanks for reading... I'll get right into the issue.

我在图像上附加了 onclick 函数.

I have an onclick function attached to an image.

<div id="mercury" onclick="displayCreations()">

JavaScript函数:

Javascript function:

function displayCreations(){
   document.getElementById("projects").style.display = "block";
}

当您到达页面时,将我显示为块的div设置为 none .此功能将显示设置为阻止,有效.

The div I'm displaying as a block is set to none once you arrive at the page. This function sets the display to block, which works.

我在为 div 中的图像设置 onclick 函数时遇到麻烦,该函数会将 display 值重新设置为没有.这似乎不适用于我当前的代码...

I'm having trouble with making an onclick function for an image inside the div that sets the display value back to none. This doesn't seem to work with my current code...

HTML:

<div id="mercury" onclick="displayCreations()">
        <img id="exit" onclick="hideCreations()" src="./assets/images/exit.png" alt="exit button" title="Leave Planet: Mercury" />
        <div id="projects">
            <h3>No creator here, but it looks like you've found some his wonderous creations...</h3>
            <ol>
                <li>Project 1</li>
                <li>Project 2</li>
                <li>Project 3</li>
            </ol>
        </div>
    </div>

Javascript:

Javascript:

function displayCreations(){
   document.getElementById("projects").style.display = "block";
}

function hideCreations(){
   document.getElementById("projects").style.display = "none";
}

当我在 google chrome 上运行此网站并单击退出"按钮时,没有任何反应,并且错误消息中也没有显示任何内容.

When I run this site on google chrome and click the 'exit' button, nothing happens and nothing is displayed in the error messages.

此链接将您引至一个著名的网站Gyazo,您可以在其中找到我在自己的视线中看到的gif图像.

This link leads you to a well-known site, Gyazo, where you can find a gif of what I see on my end.

链接:链接

对于当前的代码,我更喜欢使用javascript解决方案,也许您可​​以向我解释为什么会这样,所以我不会再遇到相同的情况了.

I'd prefer a javascript solution for my current code, and perhaps you can explain to me why this is happening so I don't get into the same situation again.

推荐答案

这是由于

It is caused due to event bubbling.Triggering an event on child propagates upward toward its parent.In your case click event on image also triggers click event on parent div.use event.stopPropagation() to prevent this from happening.

HTML:

事件 作为参数传递给事件侦听器功能

pass the event as parameter to event listener function

<img id="exit" onclick="hideCreations(event)" src="./assets/images/exit.png" alt="exit button" title="Leave Planet: Mercury" />

JS:

捕获事件并调用它的stopPropagation方法

Capture the event and call it's stopPropagation method

function hideCreations(event){
   event.stopPropagation()
   document.getElementById("projects").style.display = "none";
}

这篇关于如何防止JavaScript中的事件冒泡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆