JavaScript 警告框弹出问题

JavaScript Alert Box Popup Issue

我遇到了一个问题,即单击提交按钮后屏幕上没有出现警告框。我已经在这个论坛和网上搜索了答案,但我看不出我的代码有什么问题。与我的大多数问题一样,解决方案可能是一个简单的修复,但在查看我的代码后我似乎无法找到问题所在。感谢任何帮助。

javascript代码

<script type="text/javascript">
    function stopClock() {
        clearInterval (clockId);
        correctAns = gradeQuiz();
        alert('You have' + correctAns + 'correct of 5 in' + timer + 'seconds');
    }  
</script>

<script type="text/javascript">
    function runClock() {
        seconds++;
        document.getElementById('quizclock').value=seconds;
    }   
</script>

<script type="text/javascript">
    function startClock() {
        showQuiz();
        clockId=setInterval ("runClock()", 1000);
    }
</script>

function resetQuiz() {
    document.quiz.quizclock.value = 0;
    for (i=0; i<document.quiz.elements.length; i++)document.quiz.elements[i].disabled=false;  
    document.quiz.stop.disabled = true;
}

function showQuiz() {
    document.getElementById("quiztable").style.visibility="visible";
    document.quiz.start.disabled = true;
    document.quiz.stop.disabled = false;
}

function hideQuiz() {
    document.getElementById("quiztable").style.visibility="hidden";
}

function gradeQuiz() {
    correct=0;
    if (document.quiz.q1[1].checked) correct++;
    if (document.quiz.q2[3].checked) correct++;
    if (document.quiz.q3[0].checked) correct++;
    if (document.quiz.q4[3].checked) correct++;
    if (document.quiz.q5[2].checked) correct++;

    document.getElementById("cor1").style.backgroundColor="yellow";
    document.getElementById("cor2").style.backgroundColor="yellow";
    document.getElementById("cor3").style.backgroundColor="yellow";
    document.getElementById("cor4").style.backgroundColor="yellow";
    document.getElementById("cor5").style.backgroundColor="yellow";

    for (i=0; i<document.quiz.elements.length; i++)document.quiz.elements[i].disabled=true;  

    return correct;
}

html 用于弹出警报的按钮

<input id="stop" type="button" value="Submit Answers" onclick="stopClock()"/>

如果你删除

alert('You have' + correctAns + 'correct of 5 in' + timer + 'seconds');

您的 stopClock() 函数不会在屏幕上显示任何警报。

可能你有一个未定义的变量,检查这个工作演示

function gradeQuiz() {
  return 'something';
}

var clockId, i = timer = 0;

clockId = setInterval(function() {
  i++;

  $('h2').text(i);

}, 200);


function stopClock() {
  clearInterval (clockId);
  correctAns = gradeQuiz();

  alert('You have ' + correctAns + ' correct of 5 in  ' + timer + ' seconds');
}


$('button').on('click', stopClock);

http://jsbin.com/toyibekivu/edit?html,js,output

您需要定义变量并在 alert 中使用 seconds

将您的函数更改为:

var clockId;
var seconds = 0;
function stopClock() {
  clearInterval (clockId);
  correctAns = gradeQuiz();
  alert('You have' + correctAns + 'correct of 5 in' + seconds + 'seconds');
}  

function startClock() {
  showQuiz();
  seconds = 0;
  clockId=setInterval (runClock, 1000);
}