0

私は計算機を作成しており、次のコードを書きました。

JavaScript の場合:

function calculate() {
'use strict';
 var total;
 var quantity = document.getElementById('quantity').value;
 var price = document.getElementById('price').value;
 var tax = document.getElementById('tax').value;
 var discount = document.getElementById('discount').value;
 total = quantity*price;
 tax /= 100;
 tax++;
 total *= tax;
 tax = tax/100;
 tax = tax+1;
 total = total*tax;
 total -= discount;
 document.getElementById('total').value = total;
 return false;
 }
 function init() {
 'use strict';
 var theForm = document.getElementById('theForm');
 theForm.onsubmit = calculate;
 }
 window.onload=init;

HTML の場合:

 <div><label for="quantity">Quantity</label><input type="number"
 name="quantity" id="quantity" value="1" min="1" required></div>

 <div><label for="price">Price Per Unit</label><input type="text"
 name="price" id="tax" value="1.00" required></div>

 <div><label for="tax">Tax Rate (%)</label><input type="text"
  name="tax" id="tax" value="0.0" required></div>

 <div><label for ="discount">Discount</label><input type="text"
  name="discount" id="discount" value="0.00" required></div>

 <div><label for="total">Total</label><input type="text" name="total"
 id="total" value="0.00"></div>

 <div><input type="submit" value="Calculate" id="submit"></div>

ファイルをそれぞれ shopping.js と shopping.html として保存しましたが、shopping.html をクリックしてブラウザが開いたときに電卓が正しく動作するようにコードを相互接続する方法がわかりません。

script タグを使用して HTML コードに JavaScript コードを含めようとしましたが、うまくいきませんでした。同じディレクトリに保存する必要があるという記事をいくつか読みましたが、理解できませんでした。デスクトップの shopping というファイルに保存しましたが、ここからサポートが必要です。

ありがとうございました。

4

2 に答える 2

2

ここをチェック

price の id は「tax」でした。単なるタイプミスだと思います。代わりに、入力タイプのサンビットもボタンに変更しました。

コード:

window.onload = function() { // this loads your script when the page loads
    function calculate() {  
   'use strict';
    var total = 0;

    var quantity = document.getElementById('quantity').value;
    var price = document.getElementById('price').value;
    var tax = document.getElementById('tax').value;
    var discount = document.getElementById('discount').value;
    total = quantity * price;
    tax /= 100;
    tax++;
    total *= tax;
    tax = tax / 100;
    tax = tax + 1;
    total = total * tax;
    total -= discount;
    document.getElementById('total').value = total;
    return false;
    }
};

このコードをページに追加するか、外部ファイルから呼び出すことができます。これを html コードに入れるだけです<script src="shopping.js" type="text/javascript"></script><head>または<body>タグの中に入れます。

于 2013-06-26T18:24:39.110 に答える