2016-08-24 143 views
1

我剛開始編碼。我做了一個測驗,我希望在學生點擊正確答案時播放聲音,並在他們點擊錯誤答案時播放另一個聲音。我在網上發現了一些帖子,但他們沒有工作。誰能幫忙?先謝謝你!在javascript中點擊按鈕時添加聲音

的Javascript:

function checkAnswer(){ 
    myAnswer=$('#inputBox').val(); 
    if(myAnswer.slice(myAnswer.length-1,myAnswer.length)==" "){ 
     myAnswer=myAnswer.slice(0,myAnswer.length-1);} 
    if(currentAnswer==myAnswer){ 
     score++; 
     $('#feedback').append('<img src="tick.png">'); 
     $('#inputBox').css("background-color","green"); 
     $('#inputBox').css("color","white"); 
    } 
    else{ 
     $('#feedback').append('<img src="cross.png">'); 
     $('#inputBox').css("background-color","red"); 
     $('#inputBox').css("color","white"); 
     $('#inputBox').val($('#inputBox').val()+" (ans= "+currentAnswer+")"); 
    } 
    $('#message').append('Press ENTER again to continue'); 
    $("#inputBox").prop('disabled', true); 
    $("#gameArea").focus(); 
    gamePosition=2; 
    if(currentQuestionNumber==numberOfQuestions){gamePosition=3;} 
}//checkAnswer 

HTML:

<!DOCTYPE HTML> 
    <head> 
    <title>Quiz</title> 
    <meta name=viewport content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> 
    <link href="main.css" rel="stylesheet" type="text/css"/> 
    <link href="mainclock.css"rel="stylesheet"type="text/css"/> 
    <script src="jquery.js"></script> 
    <script src="controller.js"></script> 
    </head> 
    <body> 
    <div id="gameArea" tabindex="1"></div> 
    <div id="mainStage"> 
    </div> 
    </body> 

+0

我在HTML/JS中看不到任何'audio'元素... – Rayon

+0

請參閱['

回答

0

顯然你正在使用Jquery。所以我建議你使用基於jquery的代碼來處理這個過程,因爲less codding and so on。 所以略低於代碼複製在你的底部,並把它當過你需要聽到的聲音:

function rightAnswerChosen(){ 
    var audioFileName="audio.mp3"; 
    $("body").append("<audio src="+audioFileName+" autoplay=true loop=false/>"); 
    } 

它如此簡單! 不要忘記把你的音頻文件放在同一個目錄(文件夾)這個頁面在用'audio.mp3'替換它的名字。

您可以根據需要在Audio標籤中添加更多功能,您可以添加more attributes(例如:loop-preload-volume ...)。

就是這樣!

+0

首先感謝你的幫助。但是,即使當我在測驗底部添加代碼,或者當我在$('#inputBox').css(「color」,「white」)之間添加代碼時,mp3文件仍然不會播放。和} else {。 DId我把它放在錯誤的地方,或者我需要在我的文件夾中添加另一個JQuery?謝謝 – Shannon

+0

看看http://drax.ir/tmp/myquizPage.htm。我放了一個樣本頁來播放聲音。你可以在它的源代碼中看到描述。 –

+0

你也必須把AnswerChosen(true); if(currentAnswer == myAnswer){.and當然AnswerChosen(false);當你得到一個錯誤的答案。你可以在我的示例頁面下載源代碼和文件。 :) –

0

您可以在JavaScript中創建一個audio元素,在應用程序需要時播放。下面是如何在JS中動態啓動audio元素的示例。

var audioElement = document.createElement('audio'); 
audioElement.setAttribute('src', 'some-audio-file-here.mp3'); 
// play audio 
audioElement.play(); 
// stop audio 
audioElement.stop() 

更多信息可以在Using HTML5 audio and video找到。