javascript 单击按钮,声音播放,但按钮消失

hujrc8aj  于 2023-02-18  发布在  Java
关注(0)|答案(3)|浏览(132)

就像我在标题中说的。我想播放不同的声音,但由于某种原因,按钮上的文本在声音播放后消失。按钮仍然工作。我需要按钮保持完整。
还有,当按钮被点击时,是否有任何方法不使页面重新加载?
下面是我的代码:
浏览器:

function playSound() {
    var sounds = new Array(
    "battle.mp3"
);

$("button").html("<embed src=\""+sounds[Math.floor(Math.random()*(sounds.length+1))]+"\" hidden=\"true\" autostart=\"true\" />");

超文本标记语言

<div id="element">
<button onclick="javascript:playSound()">Try it</button>
</div>
0sgqnhkj

0sgqnhkj1#

我相信这个按钮会消失,因为你用嵌入代码替换了它的HTML。你有没有试过创建一个不同的元素(比如div)并将其作为目标?

b1zrtrql

b1zrtrql2#

您似乎要替换playSound函数中button元素内的HTML内容(请参阅此处)。请尝试将其嵌入到其他元素中,如占位符div
如果不重新加载页面,请从playSound()函数返回false

nhaq1z21

nhaq1z213#

就像其他人说的,你正在替换元素。尝试将javascript更改为:

function playSound() {
    var sounds = new Array("battle.mp3");

    $("#soundDiv").html("<embed src=\""+sounds[Math.floor(Math.random()*(sounds.length+1))]+"\" hidden=\"true\" autostart=\"true\" />");

    return false;
}

并将html设置为:

<div id="element">
    <div id="soundDiv"></div>
    <button onclick="javascript:playSound()">Try it</button>
</div>

相关问题