javascript - 新手 JavaScript 提示计算器问题

标签 javascript

所以我才刚刚开始我的 javascript 之旅。我刚刚开始接触 DOM 操作,对很多 javascript 还很陌生……你可以通过我的代码看出这一点!

我正在摆弄一个小费计算器(我猜是相当标准的新手项目),并且在 DOM 以及如何从输入(文本和 radio )中选择某些元素并让它们提交方面遇到了真正的困难。

对我下面的代码的任何建议都会很棒。我洗耳恭听,准备好为所有错误接受打屁股……但非常想知道我做错了什么!

<form class="container">
        <h2>Tip Calculator</h2>
        <p>Enter Bill Amount</p>
        <input type="text" class="input-styles" placeholder="£££" id="bill-amount">
        <p>Select Percentage Of Bill</p>
        <div class="radio-container">
            <div class="radio-styles">                        <p>10%</p>
                <input type="radio" class="radio-styles" name="tip-percent" value="0.1">
            </div>
            <div class="radio-styles">
                <p>15%</p>
                <input type="radio" class="radio-styles" name="tip-percent" value="0.15">
            </div>
              <div class="radio-styles">
                <p>20%</p>
                <input type="radio" class="radio-styles" name="tip-percent" value="0.2">
            </div>
            <div class="radio-styles">
                <p>25%</p>
                <input type="radio" class="radio-styles" name="tip-percent" value="0.25">
            </div>
        </div>
        <div class="submit-container">
            <button type="submit" name="tip-submit" id="submit-button">submit</button>
        </div>
        <div class="totals-container">
            <div class="totals">
                <h2>Tip To Pay</h2>
                <h2 id="tip-to-pay"></h2>
                <h2 id="bill-final">Total Bill To Pay</h2>
                <h2 id="bill-to-pay"></h2>
            </div>
        </div>
    </form>

下面的 JavaScript...

var bill, percent, tip, finalBill;


document.getElementById('submit-button').addEventListener('click', function() {

// get bill amount
bill = document.getElementById('bill-amount').value

//get percent amount from checkboxes
percent = document.getElementsByName('tip-percent').checked;
tip = calcTip();
finalBill = finalAmount();

// edit results in html
document.getElementById('tip-to-pay').textContent = tip;
document.getElementById('bill-to-pay').textContent = finalBill;

// display result
document.querySelector('.totals-container').style.display = 'flex';

}

function calcTip() {
    tip = percent * bill
}

function finalAmount() {
    finalBill = tip + bill
}

用我下面的笔可能会更容易看到这一点! https://codepen.io/rickwall/pen/WNbpmoW

最佳答案

HTML

在 HTML 上,您使用 <form class="container"> 包装计算器 - 表单通常用于将数据发送到网络服务器,用于提交或验证等。在这种情况下,您只是将其用作容器,因此可以坚持使用标准 <div>

这导致您提交时计算器消失的问题

JavaScript

范围 - 最初您是在全局范围而不是函数范围中定义所有变量。这通常是可以避免的,因为它可能会导致变量覆盖、丢失更改跟踪、通常出现意外行为等问题 - You can ready more about this here

函数 - 您的函数可能是您的作用域的产物,但通常您希望您的函数接受输入,并返回一个值,而不是修改函数作用域之外的值- 返回输出有助于避免意外更改,同时使用参数输入值可以实现更多控制和可读性

在这段代码中,我很想不使用这些函数并直接执行数学运算,因为它很简单且仅调用一次 - 但您可以自由地做您想做的事情

// This will change the value of tip globally, while also using set variables for percent and bill
function calcTip () {
  tip = percent * bill
}

// This allows us to return the output of our function to our chosen variable
// while also taking the inputs we want

function calcTip (percent, bill) {
  return percent * bill;
}

let tip = calcTip(0.10, 120); // returns 12;

Read more about functions from the MDN Docs

<小时/>

类型 - 在主函数中,您将检索元素的 .value ,并将它们分配给 billpercent 。但是,无论输入是“a”字符还是“2”字符,.value 都会返回一个字符串 - 当您尝试添加值时,这会导致问题,因为添加运算符 +字符串数字一起使用时会执行不同的操作。

例如,当与字符串数字一起使用时,它只会将两个变量连接在一起 - 而不是像您期望的那样将它们相加

let a = "5"; // Type: String
let b = 120; // Type: Number

a + b // "5120"

与两个数字一起使用时可以看到正确的行为

let a = 5;   // Type: Number
let b = 120; // Type: Number

a + b // 125

在您的情况下,我们可以使用 bill percent 将字符串值 parseInt(x)parseFloat(x) 转换为数字 - parseInt 转换为整数,而 parseFloat 转换为 float

<小时/>

代码片段中的代码还有一些细微的更改,但这只是您将其发布到代码审查之前的一些快速操作 - 这绝不是绝对正确的方法,有一个相当少,但希望能帮助您前进

document.getElementById('submit-button').addEventListener('click', function() {
  // Get bill amount
  let bill = parseInt(document.getElementById('bill-amount').value);

  // Get percent from selected checkbox
  /* let percent = document.getElementsByName('tip-percent'); */
  let percent = parseFloat(document.querySelector('input[name="tip-percent"]:checked').value);
  
  // No reason to have these as functions if they're simple & only called once
  let tip = percent * bill;
  let finalBill = bill + tip;

  // Add results in html
  document.getElementById('tip-to-pay').textContent = '$' + tip;
  document.getElementById('bill-to-pay').textContent = '$' + finalBill;

  // Dislay result
  document.querySelector('.totals-container').style.display = 'flex';
})
* {
  margin: 0;
  padding: 0;
}

html {
  font-family: zilla slab;
  font-size: 18px;
  font-weight: 300;
  background-image: url(imgs/restaurant.jpg);
  background-position: center;
}

.page {
  display: flex;
  justify-content: center;
  align-items: center;
}

.container {
  display: flex;
  justify-content: center;
  flex-direction: column;
  background-color: rgba(204, 238, 255, 0.9);
  padding: 50px 100px 50px 100px;
  margin-top: 2%;
  text-align: center;
  box-shadow: 0px 8px 40px rgba(0, 0, 0, 0.5), 0px 10px 20px rgba(0, 0, 0, 0.7);
  border-radius: 40px;
}

.container>h2 {
  padding-bottom: 1.6rem;
  font-size: 2.5rem;
}

.container>p {
  padding-bottom: 1rem;
  font-size: 1.5rem;
}

.container>input {
  text-align: center;
  padding: 4px;
  font-size: 1.2rem;
  width: 160px;
  margin-left: 19%;
  margin-bottom: 1rem;
}

.radio-container {
  display: flex;
  justify-content: space-between;
}

.radio-box {
  display: flex;
  text-align: center;
  align-items: center;
  flex-direction: column;
}

.radio-styles {
  margin: 10px 0 1.2rem 0;
  cursor: pointer;
  outline: none;
}

button {
  padding: 8px 40px 8px 40px;
  text-transform: uppercase;
  background-color: #fff;
  border: none;
  border-radius: 45px;
  box-shadow: 0px 8px 15px rgba(0, 0, 0, 0.3);
  transition: all 0.3s ease 0s;
  cursor: pointer;
  outline: none;
  font-family: zilla slab;
  font-weight: 300;
  font-size: 1rem;
}

.totals-container {
  display: none;
}

.totals {
  display: flex;
  flex-direction: column;
}

#bill-final {
  font-size: 2rem;
}

.totals h2 {
  padding-bottom: 1.6rem;
}
<div class="page">
  <div class="container">
    <h2>Tip Calculator</h2>
    <p>Enter Bill Amount</p>
    <input type="text" class="input-styles" placeholder="£££" id="bill-amount">
    <p>Select Percentage Of Bill</p>
    <div class="radio-container">
      <div class="radio-styles">
        <p>10%</p>
        <input type="radio" class="radio-styles" name="tip-percent" value="0.10">
      </div>
      <div class="radio-styles">
        <p>15%</p>
        <input type="radio" class="radio-styles" name="tip-percent" value="0.15">
      </div>
      <div class="radio-styles">
        <p>20%</p>
        <input type="radio" class="radio-styles" name="tip-percent" value="0.20">
      </div>
      <div class="radio-styles">
        <p>25%</p>
        <input type="radio" class="radio-styles" name="tip-percent" value="0.25">
      </div>
    </div>
    <div class="submit-container">
      <button type="submit" name="tip-submit" id="submit-button">submit</button>
    </div>
    <div class="totals-container">
      <div class="totals">
        <h2>Tip To Pay</h2>
        <h2 id="tip-to-pay"></h2>
        <h2 id="bill-final">Total Bill To Pay</h2>
        <h2 id="bill-to-pay"></h2>
      </div>
    </div>
  </div>
</div>

关于javascript - 新手 JavaScript 提示计算器问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59431667/

相关文章:

javascript - 如何编写一个 (php) Web 应用程序以向客户端发送一个 .txt 文件,其中包含客户端已插入 JS 提示框的值

javascript - 如何在 Keystone js 中添加源映射

javascript - 通过过滤函数划分数组

javascript - 在浏览器中获取现有的音频视频流

javascript - JSX 组件 + dangerouslySetInnerHTML?

javascript - jQuery QuickFit 调整不适合 div 的文本大小

javascript - 如何使用jquery在html中查找父元素内子元素(数字)的位置

javascript - D3.js 基本图表绘制示例未显示

javascript - md-select 不更新模型

javascript - 我的 API 是否应该同时包含枚举的数字和字符串表示形式?