简体   繁体   English

单击内部div也单击外部div

[英]Onclicking an inner div also onclicks the outer div

I have an outer div called paragraph and two inner divs called word . 我有一个称为paragraph的外部div和两个名为word内部div。 I also have a custom audio playing function in JS that I got from another SO post: 我还从另一个SO帖子获得了JS中的自定义音频播放功能:

<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. 当我点击段落DIV,它扮演的paragraph.mp3完美。 However when I click one of the word divs inside, it simultaneously plays both paragraph.mp3 and word.mp3 . 然而,当我点击这个词的div一个里面,它同时扮演这两种paragraph.mp3word.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. 如果使用addEventListener()而不是嵌入式onclick,则可以在传递给它的事件对象上调用stopPropagation(),以防止事件冒泡。

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 您可以通过将以下代码行添加到playsound函数来停止事件冒泡

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

This will stop JavaScript's event bubbling and propagation 这将阻止JavaScript的事件冒泡和传播

I used a simpler approach for a similar problem with embedded ★ links in my CSS buttons. 对于CSS按钮中的嵌入式★链接,我使用了更简单的方法来解决类似问题。 I set global variable embedDiv to TRUE preceding my inner onClick function. 我在内部onClick函数之前将全局变量embedDiv设置为TRUE。 In the outer onClick function, I skipped code if embedDIV was true and reset embedDiv to FALSE. 在外部的onClick功能,我跳过代码如果embedDIV是真实和复位embedDiv为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 时间地点发音

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

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