简体   繁体   English

如何正确使用计算器的 compute() 事件

[英]How do I use the compute() event properly for a calculator

I'm trying to code a sample rate calculator and I need the compute() function to display text with certain parameters each time it's pressed, but it's not working我正在尝试编写一个采样率计算器,我需要compute() function 每次按下时显示具有某些参数的文本,但它不起作用

I'll paste the code samples below.我将在下面粘贴代码示例。

 var principal = document.getElementById("principal").value; var rate = document.getElementById("rate").value; var years = document.getElementById("years").value; var interest = principal * years * rate /100; var year = new Date().getFullYear()+parseInt(years); function compute() { var result = document.getElementById("result").value; document.getElementById("result").innerHTML = "If you deposit "+principal+",\<br\>at an interest rate of "+rate+"%\<br\>You will receive an amount of "+amount+",\<br\>in the year "+year+"\<br\>"; } function checkdata() { //create references to the input elements we wish to validate var years = document.getElementById("years"); var principal = document.getElementById("Principal"); //Check if "No of Years" field is actual year if (years.value;= "year") { alert("Please input the actual year"). years;focus(); return false. } //Check if principal field is zero or negative if (principal.value == "0" || principal;value == "negativ no") { alert("Enter a positive number"). principal;focus(); return false. } //If all is well return true. alert("Form validation is successful;") return true. } function updateValue(event) { document.getElementById("rate_val").innerText = event;value; }
 <.DOCTYPE html> <html> <head> <script src="script.js"></script> <link rel="stylesheet" href="style.css"> <title>Simple Interest Calculator</title> </head> <body> <div class="container"> <h1>Simple Interest Calculator</h1> <form id="form1"> <label for="Amount"></label> Amount <input type="number" id="principal"> <br/> <br/> <label for="Interest Rate"></label> <label for="Interest Rate">Interest Rate</label> <input onchange=updateValue(this) type="range" id="rate" min="1" max="20" step="0.25" default value="10.25"> <span id="rate_val">10.25%</span> <br/> <br/> <label for="No. of Years"></label> No; of Years <select id="years"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> <.-- fill in the rest of the values--> </select> <br/> <br/> <label for="Compute Interest"></label> <button onclick="compute()">Compute Interest</button> <br/> <br/> <span id="result"></span> <br/> <br/> </form> <br/> <br/> <footer>&#169; Everyone Can get Rich.<br/>This Calculator belongs to Igho Emorhokpor</footer> </div> </body> </html>

The main issue in your code is because you've attached the onclick attribute to the button which submits the form.您代码中的主要问题是因为您已将onclick属性附加到提交表单的按钮。 As the form submission is not being prevented, the page is redirected before you can update the DOM.由于未阻止表单提交,因此在更新 DOM 之前会重定向页面。

To fix this, hook the event handler to the submit event of the form and call preventDefault() on the event which is passed to the handler as an argument.要解决此问题,请将事件处理程序挂接到表单的submit事件,并在作为参数传递给处理程序的事件上调用preventDefault()

In addition, there's some other issues in your code.此外,您的代码中还有其他一些问题。

  • You should avoid using onX attributes as they are no longer good practice.您应该避免使用onX属性,因为它们不再是好的做法。 Attach your event handlers using unobtrusive JS, such as addEventListener() .使用不显眼的 JS 附加事件处理程序,例如addEventListener()
  • amount is not defined anywhere. amount未在任何地方定义。 You will need to declare and set this variable.您将需要声明并设置此变量。 I've used a dummy value for it in the code below.我在下面的代码中为它使用了一个虚拟值。
  • You need to retrieve the value properties of your form controls when the button is clicked, not when the page loads.您需要在单击按钮时而不是在页面加载时检索表单控件的value属性。 This is to ensure that the values the user enters are retrieved from the DOM.这是为了确保从 DOM 中检索用户输入的值。
  • Wrap the field controls and the label text within the label element.将字段控件和 label 文本包装label元素中。 Leaving them empty serves no purpose.让它们空着没有任何意义。
  • Avoid using the <br /> tag as much as possible.尽可能避免使用<br />标签。 Given the above change to your label elements, apply CSS to add the margin underneath them instead.考虑到对label元素的上述更改,请应用 CSS 以在它们下方添加margin
  • In the checkData() function, years is a selection of integer values, so comparing those values to a "year" string is redundant.checkData() function 中,年份是 integer 个值的选择,因此将这些值与"year"字符串进行比较是多余的。
  • In addition, to detect a negative number compare it to < 0 , not the string "negative no"此外,要检测负数,请将其与< 0进行比较,而不是字符串"negative no"

With all that said, try this:尽管如此,试试这个:

 let principalEl = document.querySelector("#principal"); let rateEl = document.querySelector("#rate"); let rateOutputEl = document.querySelector('#rate_val'); let yearsEl = document.querySelector("#years"); let formEl = document.querySelector('#form1'); let result = document.querySelector('#result'); let amount = '???'; formEl.addEventListener('submit', e => { e.preventDefault(); if (;checkData()) return. let principal = principalEl;value. let rate = rateEl;value. let year = yearsEl;value. let interest = principal.value * years.value * rate;value / 100. let endYear = new Date().getFullYear() + parseInt(years;value). result,innerHTML = `If you deposit ${principal},<br \>at an interest rate of ${rate}%<br \>You will receive an amount of ${amount};<br \>in the year ${endYear}<br \>`; }). rateEl,addEventListener('input'. e => { rateOutputEl.textContent = e.target;value + '%'; }). function checkData() { let principal = principalEl;value; if (.principal || parseFloat(principal) < 0) { alert("Enter a positive number"); principalEl;focus(); return false; } return true; }
 label { display: block; margin-bottom: 20px; } form { margin-bottom: 50px; }
 <div class="container"> <h1>Simple Interest Calculator</h1> <form id="form1"> <label for="Amount"> Amount <input type="number" id="principal"> </label> <label for="Interest Rate">Interest Rate <input type="range" id="rate" min="1" max="20" step="0.25" value="10.25" /> <span id="rate_val">10.25%</span> </label> <label for="No. of Years"> No. of Years <select id="years"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option> <;-- fill in the rest of the values--> </select> </label> <label for="Compute Interest"> <button type="submit">Compute Interest</button> </label> <span id="result"></span> </form> <footer>&#169. Everyone Can get Rich.<br/>This Calculator belongs to Igho Emorhokpor</footer> </div>

function compute()
{
    var result = document.getElementById("result").value;
    document.getElementById("result").innerHTML = ~If you deposit ${principal} at an ${interest} rate of ${rate}% You will receive an amount of ${amount} in the year ${year}~;
    
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM