2013-06-26 27 views
0

我創建一個計算器,我寫了下面的代碼:故障javascript代碼連接到HTML代碼

爲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並且瀏覽器打開時,計算器正常工作。

我試圖通過使用腳本標記在HTML代碼中包含JavaScript代碼,但它沒有奏效。我閱讀了一些文章,說你必須將它們保存在同一個目錄中,但我不明白這一點。我將它們保存在桌面上的一個名爲shopping的文件中,我需要從這裏獲得一些幫助。

謝謝。

+0

您能告訴我們您嘗試使用的腳本標籤嗎? – Dan455

+0

我猜你需要在HTML的塊內移動 Sergio

+0

@ user1804697,忘了問:是在這裏工作http://jsfiddle.net/nLSXS/? – Sergio

2

如果他們在同一目錄下,你可以調用js文件在你的HTML頁面,如下所示:

<script src="shopping.js" type="text/javascript"></script> 

如果這是你必須反映在src行的文件夾中:文件夾名/ filename

這就是如何讓外部的js文件進入你的HTML文檔。但是,如果您將js代碼直接放入HTML文檔的腳本標記中,但它仍然無法正常工作,那麼代碼存在問題。