Javascript 提示计算器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21272696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript Tip Calculator
提问by user3221658
I'm working on a tip calculator in Javascript where the user should be able to type in the amount of the bill, push "calculate", and see both the tip and the total (which includes the bill and the tip).
我正在使用 Javascript 开发小费计算器,用户应该能够在其中输入账单金额,按下“计算”,并查看小费和总额(包括账单和小费)。
I've been working at this for a while, but can't seem to make it work correctly.
我已经在这方面工作了一段时间,但似乎无法使其正常工作。
<!DOCTYPE html>
<head>
<title>Tip Calculator</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="wrapper">
<header>
<h1>Tip Calculator</h1>
</header>
<form>
Amount: $<input id="bill" type="text">
<br>
<button onclick="calc()">Calculate</button>
<br>
Tip: <span id="tip"></span>
<br>
Total: <span id="total"></span>
</form>
</div>
<script>
function calc() {
var bill = document.getElementById('bill').value;
var tip = bill * .15;
var total = bill + tip;
document.getElementById("tip").innerHTML= "$"+(tip).toFixed(2);
document.getElementById("total").innerHTML= "$"+(total).toFixed(2);
}
</script>
</body>
Any suggestions?
有什么建议?
回答by m59
You have a few problems. You need the event passed by the click function so that you can stop the form from submitting traditionally, which causes a page refresh. The best practice is to attach the click handler with javascript. You also need to convert the string value of the input into an actual number so that it can be used for addition.
你有几个问题。您需要点击函数传递的事件,以便您可以阻止表单传统的提交,这会导致页面刷新。最佳做法是使用 javascript 附加点击处理程序。您还需要将输入的字符串值转换为实际数字,以便用于加法。
// get element references - no need to keep repeating this in the function
var myBtn = document.getElementById('my-button');
var tipElem = document.getElementById("tip");
var totalElem = document.getElementById("total");
//attach click event listener
myBtn.addEventListener('click', calc);
//the event object is passed to this automatically - I'm assigning it to "e"
function calc(e) {
//prevent the default action - form submit / page refresh
e.preventDefault();
var input = document.getElementById('bill');
//convert string value to Number
var bill = parseFloat(input.value);
var tip = bill * 0.15;
var total = bill + tip;
//textContent is better than innerHTML for setting text
tipElem.textContent = "$"+(tip).toFixed(2);
totalElem.textContent = "$"+(total).toFixed(2);
}
Here is the markup I recommend:
这是我推荐的标记:
<form>
<p>Amount: $<input id="bill" type="number"></p>
<button id="my-button">Calculate</button>
<p>Tip: <span id="tip"></span></p>
<p>Total: <span id="total"></span></p>
</form>
<br>
should not be used for layout. Instead, you can use display: block
on the elements that should go to a new line. Many elements do this by default, such a <p>
. I also changed the input type to number
because that that seems more appropriate here.
<br>
不应用于布局。相反,您可以display: block
在应该换行的元素上使用。许多元素默认执行此操作,例如<p>
. 我还将输入类型更改为 ,number
因为这在这里似乎更合适。
Unfortunately, some people are going to suggest and argue that inline js (that's any kind of javascript in your html, like onclick
) is ok to use. It isn't. I hope you will read some of these results: Why is inline JS bad?
不幸的是,有些人会建议并争辩说,可以使用内联 js(即 html 中的任何类型的 javascript,例如onclick
)。不是。我希望你能阅读其中的一些结果:为什么内联 JS 不好?
回答by Rhyono
Forms are typically used to submit data to a server for various reasons. However, they have some benefits even when everything is being done on the same page (such as being able to press enter in any input and still have it submit without using extra code). What I did here was give it an action
of the function you wanted to use and then changed your button to a standard submit
.
出于各种原因,表单通常用于向服务器提交数据。但是,即使所有内容都在同一页面上完成,它们也有一些好处(例如,可以在任何输入中按 Enter 键,并且仍然可以在不使用额外代码的情况下提交)。我在这里所做的是给它一个action
你想要使用的功能,然后将你的按钮更改为标准的submit
.
There are various methods for taking a string and making it into a number, I used the simplest here: Number()
. I used it on bill
in order to make the total_bill
display properly (instead of adding two strings together which just places them side by side). I changed total
to total_bill
for the variable because it is just not a good idea to name multiple things the same (e.g. the id and the variable). I missed the bill/bill, but I'll leave it as is because it does usually still work (like here).
取一个字符串并把它变成数字的方法有很多种,我这里用的是最简单的:Number()
. 我使用它bill
是为了使total_bill
显示正确(而不是将两个字符串并排放置在一起)。我换total
到total_bill
的变量,因为它仅仅是不是一个好主意来命名多的东西是相同的(如ID和变量)。我错过了账单/账单,但我会保持原样,因为它通常仍然有效(就像这里)。
Lastly, toFixed()
takes a number and makes it a string. Which means you have to make sure it's a number and not already a string. This is why Number()
was used again before outputting.
最后,toFixed()
取一个数字并使其成为字符串。这意味着您必须确保它是一个数字而不是一个字符串。这就是为什么Number()
在输出之前再次使用的原因。
Try this:
试试这个:
<!DOCTYPE html>
<head>
<title>Tip Calculator</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="wrapper">
<header>
<h1>Tip Calculator</h1>
</header>
<form action="javascript:void(calc())">
Amount: $<input id="bill" type="text">
<br>
<input type="submit" value="Calculate">
<br>
Tip: <span id="tip"></span>
<br>
Total: <span id="total"></span>
</form>
</div>
<script>
function calc() {
var bill = Number(document.getElementById('bill').value);
var tip = bill * .15;
var total_bill = bill + tip;
document.getElementById("tip").innerHTML= "$"+Number(tip).toFixed(2);
document.getElementById("total").innerHTML= "$"+Number(total_bill).toFixed(2);
}
</script>
</body>
回答by Kevin Seifert
Try a standard input button
尝试标准输入按钮
<input type="button" onclick="calc()" value="Calculate">
Also, the toFixed() method doesn't necessarily exist on the var. In testing in Chrome, it will work however if you explicitly cast to number
此外,toFixed() 方法不一定存在于 var 中。在 Chrome 中进行测试时,如果您显式转换为数字,它将起作用
document.getElementById("tip").innerHTML= "$"+(new Number(tip)).toFixed(2);
document.getElementById("total").innerHTML= "$"+(new Number(total)).toFixed(2);
回答by Marc
Try to use this
尝试使用这个
function calc() {
var bill = $("#bill").value;
var tip = bill * .15;
var total = bill + tip;
document.getElementById("tip").innerHTML= "$"+(tip).toFixed(2);
document.getElementById("total").innerHTML= "$"+(total).toFixed(2);
}
Also try to create JSFIDDLEfor you to create some demo.
还尝试为您创建JSFIDDLE来创建一些演示。
回答by traditional
The problem is when you do document.getElementById('bill').value;
it returns string
value, not the Number
value. In order to have toFixed
method, you need to parse the value as Number by using parseInt(document.getElementById('bill').value,10);
问题是当你这样做时,document.getElementById('bill').value;
它会返回string
值,而不是Number
值。为了有toFixed
方法,您需要使用以下方法将值解析为 NumberparseInt(document.getElementById('bill').value,10);
Also you need to return false;
to stop submitting the form.
您还需要return false;
停止提交表单。
回答by Yuriy Galanter
Your form is being submitted hence it is losing values. There're many way to avoid this - one - define your form as
<form onsubmit="return false">
Your total won't calculate because bill is read as string. One way to force it into number is multiply by 1, so total will be
var total = bill*1 + tip;
您的表单正在提交,因此正在丢失值。有很多方法可以避免这种情况 - 一种 - 将您的表单定义为
<form onsubmit="return false">
您的总数不会计算,因为 bill 被读取为字符串。将其强制为数字的一种方法是乘以 1,因此总数将为
var total = bill*1 + tip;
Here's working demo: http://jsfiddle.net/5GQZ8/
这是工作演示:http: //jsfiddle.net/5GQZ8/
回答by Coder
<!DOCTYPE html>
<head>
<title>Tip Calculator</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="wrapper">
<header>
<h1>Tip Calculator</h1>
</header>
<form>
Amount: $<input id="bill" type="text">
<br>
<a onclick="calc()">Calculate</a>
<br>
Tip: <span id="tip"></span>
<br>
Total: <span id="total"></span>
</form>
</div>
<script>
function calc() {
var bill = document.getElementById('bill').value;
var tip = bill * .15;
var btotal = bill + tip;
document.getElementById("tip").innerHTML= "$"+Number(tip);
document.getElementById("total").innerHTML= "$"+Number(btotal);
}
</script>
</body>