0

我正在尝试创建一个代码,该代码将询问用户有多少 X、Y 等项目,并使用 Javascript 计算欠款总额,并打印所有购买项目的摘要(收据)。抱歉,新手问题,试图在没有任何正式培训的情况下学习代码。感谢所有的帮助!

<html>

<head>

<title>Cost Calculator</title>

<script language="javascript" type="text/javascript">
function packageTotal(){
    //Enter in prices here
    var applePrice = 1;
    var bookPrice = 2;
    x = Number(document.calculator.books.value);
    y = Number(document.calculator.apples.value);
    var b = applePrice*x + bookPrice*y;
    var p = applePrice*x + bookPrice*y + .5;

    if (document.getElementById('noBag').checked) {
    //Basic package is checked
    document.calculator.total.value = b;
        } else if (document.getElementById('yesBag').checked) {
    //Pro package is checked
    document.calculator.total.value = p;
        }

    //Want to add summary of purchase
    //document.write("You want " + x " books and " y " apples.");


}

</head>

<body>

<!-- Opening a HTML Form. --> 
<form name="calculator">

<!-- Here user will enter the number of Books and Apples --> 
Enter Number of Books: <input type="text" name="books"> 
<br />

Enter the Number of Apples: <input type="text" name="apples">
<br />

<br />
<input type="radio" name="item" id="noBag" value="No" /> noBag
<input type="radio" name="item" id="yesBag" value="Yes" checked /> yesBag

<!-- Here result will be displayed. -->

<input type="button" value="Submit" onclick="packageTotal();">

Your Total Price is: <input type="text" name="total">

</form>


</body>
</html>
4

1 回答 1

1

从问题中不清楚,但如果这是问题:

//Want to add summary of purchase
//document.write("You want " + x " books and " y " apples.");

那么那肯定会破裂。document.write仅在文档仍在加载时添加到当前文档。如果您之后调用它,它将隐式打开一个要写入的新文档,从而破坏当前页面。一般document.write都是坏事。

(由于缺少+连接运算符,还会出现一些细微的语法错误)

如果要向页面写入任意文本,请创建一个占位符元素:

<div id="message"></div>

然后设置其文本内容:

function setTextContent(element, text) {
    element.innerHTML = ''; // remove current content
    element.appendChild(document.createTextNode(text));
}

var message = document.getElementById('message');
setTextContent(message, 'You want '+x+' books and '+y+' apples.');

(元素上有一个textContent属性,您也可以使用它来代替函数,但在 IE<9 上不支持使用它innerText。在这种情况下,简单地将消息直接写入innerHTML也可以,但这是一个坏习惯,因为它与用户输入一起使用时会导致 HTML 注入安全漏洞。)

于 2013-08-02T13:40:31.323 回答