Javascript代码中断循环

时间:2015-03-03 08:59:44

标签: javascript loops for-loop

我一直在努力为课堂做这件事,但我似乎无法让它发挥作用。我需要有单选按钮来选择4个硬币中的一个。 Q,d,N,P。然后是一个值为10的选择框。当我更改选择时,Java需要添加所选的硬币数量,并显示总数,并显示许多硬币。我有添加部分,但是当我添加循环时,它会破坏项目的添加部分。我不知道我是否有正确的循环,但是现在我想知道为什么我的代码在添加循环时会中断?我到目前为止的守则。

<script type="text/javascript">
    function doCalculate() {
        //Variable for calculation
        Q = document.getElementById('txtMoney').value;

        //If statements for selecting the correct radiobutton
        if (document.getElementById('rbQ').checked) {
            answer = Q * .25;
        }
        if (document.getElementById('rbD').checked) {
            answer = Q * .10;
        }
        if (document.getElementById('rbN').checked) {
            answer = Q * .05;
        }
        if (document.getElementById('rbP').checked) {
            answer = Q * .01;
        }


        //show results
        document.getElementById('results').innerHTML = "$ " + answer + "<br>Dollars and Cents"


        //variables for coins using ID txtMoney from Select
        loopCounter = document.getElementById('txtMoney').value

        //If radio of coin is checked and loopcounter is higher then 0 run for loop
        if (document.getElementById('rbQ').checked && loopCounter > 0;) {
            document.getElementById('quarter').src = "quarter.gif";

        }

        resultsString = ""

        //for loop to count via select box value, and display that many images
        // of which ever coins radio is checked.
        for (x = 0; x < loopCounter; x++) {
            resultsString = loopCounter + quarter.gif
            //write to results2 via innerHTML
            document.getElementById('results2').innerHTML = resultsString;
        }
    }
</script>

1 个答案:

答案 0 :(得分:0)

在为resultsString分配值时,您缺少字符串分隔符,因此代码将循环到gif对象中的quarter属性,这自然不存在

resultsString = loopCounter + "quarter.gif";

在循环之前if条件中有一个分号太多:

if (document.getElementById('rbQ').checked && loopCounter>0) {