我有两个文本框,其值为“是”和“否”。当我在第一个文本框中输入“是”时,它会发出嗡嗡声,其余的文本框也会出现同样的情况。当我在相应的文本框中输入正确的值时,声音应该只播放一次。
在我的例子中,声音一次又一次地重复.我不知道可能是什么原因。
<input type="text" id="question"/>
<input type="text" id="question1"/>
<audio src="beep.mp3" id="mp3" preload="auto"></audio>
function checkResults() {
if ($('#question').val().toLowerCase() == 'yes') {
document.getElementById("mp3").play();
}
if ($('#question1').val().toLowerCase() == 'no') {
document.getElementById("mp3").play();
}
}
$('input').blur(checkResults);发布于 2014-08-17 16:39:32
声音不止一次播放,因为您正在检查blur事件,因此每次用户模糊出框时,只要在框中有正确的答案,声音就会重放。相反,您应该检查keyup事件。
示例:
var answers = {
'question': 'yes',
'question1': 'no'
};
function checkResults() {
var $this = $(this), val = $this.val().toLowerCase();
for (var k in answers) {
if (answers.hasOwnProperty(k)) {
if (answers[$this.attr('id')] && answers[$this.attr('id')] === val) {
play();
}
}
}
}
function play() {
var sound = document.getElementById('mp3');
sound.pause();
sound.currentTime = 0;
sound.play();
}
$('input').on('keyup', checkResults);JSFiddle演示
http://jsfiddle.net/7ahpgt5s/
https://stackoverflow.com/questions/25350661
复制相似问题