[英]Onclicking an inner div also onclicks the outer div
我有一个称为paragraph
的外部div和两个名为word
内部div。 我还从另一个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();
}
}
当我点击段落DIV,它扮演的paragraph.mp3
完美。 然而,当我点击这个词的div一个里面,它同时扮演这两种paragraph.mp3
和word.mp3
。 我该如何阻止这种情况的发生?
如果使用addEventListener()而不是嵌入式onclick,则可以在传递给它的事件对象上调用stopPropagation(),以防止事件冒泡。
word1Div.addEventListener('click', function(event) {
event.stopPropagation();
playSound(this, 'word1.mp3');
}
您可以通过将以下代码行添加到playsound函数来停止事件冒泡
const e = window.event; e.cancelBubble = true; if (e.stopPropagation) { e.stopPropagation(); }
这将阻止JavaScript的事件冒泡和传播
对于CSS按钮中的嵌入式★链接,我使用了更简单的方法来解决类似问题。 我在内部onClick函数之前将全局变量embedDiv设置为TRUE。 在外部的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')">★</span></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.