我有两个文本框,其值为“是”和“否”。当我在第一个文本框中键入“是”时,它会发出蜂鸣声,并且剩余的文本框也会出现相同的情况。当我在相应的文本框中输入正确的值时,声音应该只播放一次。
在我的情况下,声音一次又一次地重复......我不知道可能是什么原因。
<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);
答案 0 :(得分:1)
由于您正在检查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演示