家庭作业帮助 - Javascript硬币罐

时间:2013-05-09 22:28:36

标签: javascript

我们的老师要求我们制作一罐硬币,计算我们有多少便士,硬币等,然后给出总金额。

这是他希望我们使用的模板

https://online.pcc.edu/content/enforced/70599-22278.201302/labs/frameworks/Lab4Template.html?_&d2lSessionVal=0Zb6SMZBBcQ8ENPN4HdQk4js0

他希望我们在用逗号分隔的同一文本框中输入便士,镍币,硬币,四分之一。我的问题是,我该怎么做?我不知道如何在JavaScript中这样做。任何人都可以带领我朝着正确的方向前进。

这是代码

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title> 122 Lab 4 Template </title>
    <meta name="author" content="Lee Middleton" />
    <meta name="keywords" content="CIS122" />
    <meta name="description" content="CIS 122 Lab 4" />
    <link rel="stylesheet" type="text/css" href="/content/enforced/70599-22278.201302/labs/frameworks/../../new122_Style.css?_&amp;d2lSessionVal=FeMQRN1p4YNBW7SRb8H38sRQW" />
    <style type="text/css">
        .container {
            border: 1px solid black;
            border-radius: 15px;
            width: 350px;
            margin: 25px auto;
            padding: 10px;
        }
        .result {
            width: 175px;
            float: left;
        }
        p { margin: 5px 0 0 5px;}
        .clear { clear: both; }
        input[type='button'] {
            margin: 10px 0 0 5px;
        }
    </style>
    <script language="javascript">
        function countCoins()
        {
            // Add your code here to count the coins and display your answers
        }
    </script>

<script type="text/javascript" src="/d2l/common/mathjax/2.0/MathJax.js?config=MML_HTMLorMML%2c%2fd2l%2flp%2fmath%2fdisplay%2fconfig.js%3fv%3d9.4.1000.156-10" ></script></head>

<body>
<h1>CIS 122 Lab 4</h1>
<div class="container">
<h2>SORT-O-COIN</h2>
<form name="clubForm" style="margin-bottom: 10px;">
<div style="margin-left: 10px;">Coin Jar <input name="coinJar" size="40" type="text" /></div>
<p>Number of pennies: <span name="pennies"></span></p>
<p>Number of nickels: <span name="pennies"></span></p>
<p>Number of dimes: <span name="pennies"></span></p>
<p>Number of quarters: <span name="pennies"></span></p>
<p>Number of half-dollars: <span name="pennies"></span></p>
<p>Total number of coins: <span name="totalCoins"></span></p>
<p>Total value: <span name="totalValue"></span></p>
<input value="Count the coins" onclick="countCoins()" type="button" /></form></div>
</body>
</html>

3 个答案:

答案 0 :(得分:1)

您的文字,使用String.split

以逗号分隔
var valuesArray = yourInput.split(',');

它提供了由,分割的值数组。它们可以通过索引访问。

var first = valuesArray[0];
var second = valuesArray[1]; //and so on...

至于计数,你可以从那里弄清楚。

答案 1 :(得分:0)

首先,您需要拆分文本框的文本。

var value = mystring.split(",");

然后浏览数组中的每个项目。

首先,您将值[x]添加到总硬币数中。 然后将硬币类型的id设置为值[x]的值,例如

document.getElementById('pennies').innerHTML = value[0];

然后取值[x]乘以硬币值,例如

totalamount = totalamount + (value[x] * 1);

用于便士并将其添加到总金额中。 最后,您可以设置总值      document.getElementById('totalValue')。innerHTML = totalamount。

总的来说,它会是这样的:

function countCoins () {
 // Add your code here to count the coins and display your answers
var coinJar = document.getElementsByName("coinJar")[0].value; //first get the value
var coinArray = coinJar.split(","); //split it
var values = [0.01, 0.05, 0.10, 0.25, 0.50]; //coin values
var ids = ['pennies', 'nickels', 'dimes', 'quarters', 'halfdollars']; //ids of coins*
var total = 0; //total dollar amount
var coinnumber = 0; //amount of coins.

for (var i = 0; i < coinArray.length; i++) {
    var currentvalue = parseInt(coinArray[i]); //value of current coin
    document.getElementsByName(ids[i])[0].innerHTML = currentvalue; //set the html
    total += currentvalue * values[i];
    coinnumber += currentvalue;

}
document.getElementsByName('totalValue')[0].innerHTML = total;
document.getElementsByName('totalCoins')[0].innerHTML = coinnumber;


}

JSFiddle

答案 2 :(得分:0)

您可以将此作为参考。

注意:这可能不完整,可能仍需要完成某些操作,但它会演示您应该知道的所有内容,处理此类问题,或者为您提供搜索/提出有关问题的具体信息。你可以学习。

CSS

.container {
    border: 1px solid black;
    border-radius: 15px;
    width: 350px;
    margin: 25px auto;
    padding: 10px;
}
.result {
    width: 175px;
    float: left;
}
p {
    margin: 5px 0 0 5px;
}
.clear {
    clear: both;
}
input[type='button'] {
    margin: 10px 0 0 5px;
}

HTML

<h1>CIS 122 Lab 4</h1>

<div class="container">

<h2>SORT-O-COIN</h2>

    <form id="clubForm" style="margin-bottom: 10px;">
        <div style="margin-left: 10px;">Coin Jar
            <input id="coinJar" size="40" type="text">
        </div>
        <p>Number of pennies: <span id="pennies"></span>

        </p>
        <p>Number of nickels: <span id="nickels"></span>

        </p>
        <p>Number of dimes: <span id="dimes"></span>

        </p>
        <p>Number of quarters: <span id="quarters"></span>

        </p>
        <p>Number of half-dollars: <span id="halfDollars"></span>

        </p>
        <p>Total number of coins: <span id="totalCoins"></span>

        </p>
        <p>Total value: <span id="totalValue"></span>

        </p>
        <input value="Count the coins" id="countCoinsButton" type="button">
    </form>
</div>

的Javascript

(function (global) {
    var types = "pennies nickels dimes quarters halfDollars".split(" "),
        worths = "0.01 0.05 0.10 0.25 0.5".split(" "),
        numTypes = types.length,
        totals = {},
        coinJar,
        clubForm;

    function countCoins() {
        var values = coinJar.value.trim().split(","),
            length = Math.min(numTypes, values.length),
            i = 0,
            coins,
            value;

        clubForm.reset();
        while (i < length) {
            value = values[i].trim();
            if (value !== "") {
                coins = parseInt(value, 10) || 0;
                totals[types[i]] = (totals[types[i]] || 0) + coins;
                totals["coins"] = (totals["coins"] || 0) + coins;
                totals["value"] = parseFloat(((totals["value"] || 0) + (coins * parseFloat(worths[i]))).toFixed(2));
            }

            i += 1;
        }

        length = types.length;
        i = 0;
        while (i < length) {
            document.getElementById(types[i]).textContent = totals[types[i]] || 0;
            i += 1;
        }

        document.getElementById("totalCoins").textContent = totals["coins"] || 0;
        document.getElementById("totalValue").textContent = totals["value"] || "0.00";
    }

    global.addEventListener("load", function onLoad() {
        global.removeEventListener("load", onLoad);
        clubForm = document.getElementById("clubForm");
        coinJar = document.getElementById("coinJar");
        document.getElementById("countCoinsButton").addEventListener("click", countCoins, false);
    }, false);
}(window))

jsfiddle