如果js上给出的代码是正确的,那么音频将如何播放



我目前正在练习我的html和js技能,我有这个代码,当我点击解锁按钮时,音频会自动播放,但问题是即使解锁代码是错误的,音频仍然会播放这是我的html在按钮和音频上

音频标签:

<audio id="music" src="bgmusic.mp3" controls hidden loop></audio>

按钮标签:

<button id="unlock" class="round pink"  onclick="playAudio()">
Unlock
</button>

这是我当前用于按钮上的onlick事件的js

var x = 
document.getElementById("music");
function playAudio() {
x.play();
}

这是我目前的语法,但我想发生的是,只有当我输入正确的代码时,音频才会播放

这是解锁代码功能的js函数:

var number = 0;
$('#unlock').on('click', function(event) {
event.preventDefault();
event.stopPropagation();
$('#textMachine').css('display', 'inline-block');
var code = '';
$.each($('.code'), function(i, v) {
code += $(v).val();
});

if(code == '30')
{
// success
var machine = $('#textMachine').slotMachine({
active: 0,
delay: 500,
randomize : function(activeElementIndex){
return 3;
}
});
machine.setRandomize(3);
machine.shuffle(5, function(){
answerCorrect();
});
} else {

if(number == 3) { number = 0; }
// fail
var machine = $('#textMachine').slotMachine({
active: 1,
delay: 500,
randomize : function(activeElementIndex){
return number;
}
});

machine.shuffle(5, function(){
number++;
});
}

});
var answerCorrect = function() {
$('.login-form').fadeOut();
$('.congratulation-text').fadeIn();
$('.success-area').css('display','block');


};

})();

实际上你可以做这个

function playSound () {
var audio = new Audio('audio_file.mp3');
audio.play();
}

你可以在你的按钮或你的功能上调用它

最新更新