我正在尝试使用通过提交按钮通过表单获取的信息,进行一些处理,然后将其打印到网页上,防止它通过包含提交给Web服务器(返回false )。
以下是该页面的代码:
<html>
<head>
<title>SmithSellsStuff</title>
</head>
<body>
<a href="week1-1.html">I'm too cheap to buy something nice</a>
<script>
var myData = {
price: "4.25",
taxRate: "0.07",
shipRate: "0.02"
};
myData.calculateTotal = function() {
myData.name = document.getElementById("name");
myData.date = document.getElementById("date");
myData.numItems = document.getElementById("number of items");
var itemTotal = myData.numItems * myData.price;
var taxTotal = (myData.numItems * myData.price) * myData.taxRate;
var shipTotal = (myData.numItems * myData.price) * myData.shipRate;
document.writeln(itemTotal);
document.writeln(taxTotal);
document.writeln(shipTotal);
};
</script>
<form>
</p>
<label>Name: <input type="text" name="name" id="name" tabindex="1"/> </label>
</p>
<label>Delivery Date: <input type="date" name="date" id="date" tabindex="2"/></label>
</p>
<label>Number of items: <input type="number" name="number of items" id="number of items" tabindex="3"/></label>
</p>
<input type="submit" onclick="calculateTotal(); return false;"/>
</form>
</body>
</html>
在第一页上,我有一个简单的表单,其中包含名称,日期,项目总数和提交按钮的字段。我得到的一个错误是onclick标签。它说“_kof_1”已定义但从未使用过。我不认为它允许我的calculateTotal函数调用。
答案 0 :(得分:1)
这是因为该函数未在全局范围内声明,而是作为myData
的属性。
myData.calculateTotal = function() {
要解决此问题,只需将呼叫更改为:
<input type="submit" onclick="myData.calculateTotal(); return false;"/>
此外,由于您想从文本字段中获取项目的名称,日期和数量,您必须获取.value
属性以获取输入字段的内容,如下所示:
myData.name = document.getElementById("name").value;
myData.date = document.getElementById("date").value;
myData.numItems = parseInt(document.getElementById("number of items").value);
答案 1 :(得分:0)
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<a href="week1-1.html">I'm too cheap to buy something nice</a>
<script>
function calculateTotal()
{
alert("hai");
var price="4.25";
var taxRate="0.07";
var shipRate="0.02";
var name = document.getElementById("name");
var date = document.getElementById("date");
var numItems = document.getElementById("number_of_items").value;
alert(numItems);
var itemTotal = numItems * price;
var taxTotal = (numItems * price) * taxRate;
var shipTotal = (numItems * price) * shipRate;
document.writeln("Total Items:"+itemTotal+"\tTax :"+taxTotal+"\tshipTotal:"+shipTotal);
}
</script>
<form>
<p>
<label>Name: <input type="text" name="name" id="name" tabindex="1"/> </label>
</p>
<label>Delivery Date: <input type="date" name="date" id="date" tabindex="2"/></label>
<p>
<label>Number of items: <input type="number" name="number_of_items" id="number_of_items" tabindex="10"/></label>
</p>
<input type="submit" onclick="calculateTotal()"/>
</form>
</body>
</html>
警告只是为了知道方法是否正在调用,希望这会对你有帮助