How to prevent event bubbling in javascript

本秂侑毒 提交于 2019-11-30 05:39:40

问题


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

I have an onclick function attached to an image.

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

Javascript function:

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

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.

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:

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

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

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

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

Link: Link

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.


回答1:


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:

Capture the event and call it's stopPropagation method

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


来源:https://stackoverflow.com/questions/48328992/how-to-prevent-event-bubbling-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!