简体   繁体   中英

Onclicking an inner div also onclicks the outer div

I have an outer div called paragraph and two inner divs called word . I also have a custom audio playing function in JS that I got from another SO post:

<div class="paragraph" onclick="playSound('this, paragraph.mp3');">
    <div class="word" onclick="playSound('this, word1.mp3');">Word1</div>
    <div class="word" onclick="playSound('this, word2.mp3');">Word2</div>
</div>


function playSound(el,soundfile) {
    if (el.mp3) {
        if(el.mp3.paused) el.mp3.play();
        else el.mp3.pause();
    } else {
        el.mp3 = new Audio(soundfile);
        el.mp3.play();
    }
}

When I click the paragraph div, it plays the paragraph.mp3 perfectly. However when I click one of the word divs inside, it simultaneously plays both paragraph.mp3 and word.mp3 . How can I stop this from happening?

If you use addEventListener() instead of inline onclick, you can call stopPropagation() on the event object passed to it to prevent the event from bubbling up.

word1Div.addEventListener('click', function(event) {
    event.stopPropagation();
    playSound(this, 'word1.mp3');
}

You can stop the event bubbling by adding these lines of code to your playsound function

 const e = window.event; e.cancelBubble = true; if (e.stopPropagation) { e.stopPropagation(); } 

This will stop JavaScript's event bubbling and propagation

I used a simpler approach for a similar problem with embedded ★ links in my CSS buttons. I set global variable embedDiv to TRUE preceding my inner onClick function. In the outer onClick function, I skipped code if embedDIV was true and reset embedDiv to FALSE.

<script>
var embedDiv = false;

function tm(wikiPlace) { 
      if(!embedDiv) { place(wikiPlace); alert("( " + wikiPlace + " ) -- " + tym); } 
      embedDiv = false;
}
</script>

<div onclick="tm('Argentina')">Argentina<span 
     onclick="embedDiv=true;go('Argentina')">&starf;</span></div>

时区-其他按钮

Time-Place-Pronounce

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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