MAR*_*WAN 1 html javascript onclick
我有一个外部div paragraph和两个内部div被称为word.我在JS中也有一个自定义音频播放功能,我从另一个SO帖子中获得:
<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();
}
}
Run Code Online (Sandbox Code Playgroud)
当我点击段落div时,它会paragraph.mp3完美播放.但是,当我单击其中一个单词div时,它同时播放两个paragraph.mp3和word.mp3.我怎么能阻止这种情况发生?
小智 7
如果使用addEventListener()而不是inline onclick,则可以对传递给它的事件对象调用stopPropagation()以防止事件冒泡.
word1Div.addEventListener('click', function(event) {
event.stopPropagation();
playSound(this, 'word1.mp3');
}
Run Code Online (Sandbox Code Playgroud)