.blur()声音通知

.blur() sound notifications

本文关键字:通知 声音 blur      更新时间:2023-09-26

我有两个值为" yes "answers" no "的文本框。当我在第一个文本框中输入"yes"时,它会发出嘟嘟声,剩下的文本框也会发生同样的情况。当我在相应的文本框中输入正确的值时,声音应该只播放一次

在我的情况下,声音一遍又一遍地重复……我不知道是什么原因。

<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);

声音播放不止一次,因为你正在检查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/