【问题标题】:JS play sound on button clickJS在按钮单击时播放声音
【发布时间】:2018-08-17 07:18:39
【问题描述】:
我正在使用选择输入(一个元素将始终被“选中”)。现在,当用户点击 demoPlay 按钮时,应该播放当前选择的声音,请参阅我的代码。
<select class="form-control" id="notificationSounds" name="notificationSound">
<option value="1">Beep sound</option>
<audio id="demoSound1">
<source src="/sounds/beep.ogg" type="audio/ogg">
Playing audio elements is not supported by your browser
</audio>
<option value="2" selected>Funny sound</option>
<audio id="demoSound2">
<source src="/sounds/frog.ogg" type="audio/ogg">
Playing audio elements is not supported by your browser
</audio>
</select>
<button type="button" id="demoPlay" class="btn btn-success">Play sound</button>
<script type="text/javascript">
$(document).ready(function() {
$("#demoPlay").click(function() {
selected_element = "notificationDemo_" + $('#notificationSounds').find(":selected").val();
$("#selected_element").play()
})
})
</script>
由于某种原因它返回:
返回:未捕获的类型错误:$(...).play 不是函数
【问题讨论】:
标签:
javascript
jquery
audio
【解决方案1】:
这里有几个问题。首先,您不能将audio 元素放在 select 中,只能放置option 元素。把它们移到外面。
其次,您使用字符串文字 '#selected_element' 作为 jQuery 选择器,而 selected_element 是一个变量,您需要将其 value 连接到选择器,即。 $('#' + selected_element).
您也在寻找#notificationDemo_N 元素,而audio 实际上具有demoSoundN 的id。
最后,play() 不是 jQuery 方法。您要么需要 trigger() 元素上的底层事件,要么直接在 Element 对象上调用 play()。
说了这么多,试试这个:
<select class="form-control" id="notificationSounds" name="notificationSound">
<option value="1">Beep sound</option>
<option value="2" selected>Funny sound</option>
</select>
<audio id="demoSound1">
<source src="/sounds/beep.ogg" type="audio/ogg">
Playing audio elements is not supported by your browser
</audio>
<audio id="demoSound2">
<source src="/sounds/frog.ogg" type="audio/ogg">
Playing audio elements is not supported by your browser
</audio>
<button type="button" id="demoPlay" class="btn btn-success">Play sound</button>
$(function() {
$("#demoPlay").click(function() {
var selected_element = "demoSound" + $('#notificationSounds').val();
$('#' + selected_element).get(0).play();
});
});
【解决方案2】:
play() 不是 jQuery 函数,因此您需要访问底层 DOM 对象才能使用它。
$("#selected_element").get(0).play()