简体   繁体   English

制作基本的Javascript计算器

[英]Making a basic Javascript calculator

jsfiddle demo jsfiddle演示

Bear with me, total newb here. 忍受我,这里总是newb。

I'm trying to make a simple multiplication calculator, as a experimentation with Javascript. 我正在尝试制作一个简单的乘法计算器,作为Javascript的实验。

The catch is that - 抓住的是-

  1. No libraries, just pure javascript. 没有库,只有纯JavaScript。
  2. Javascript must be unobtrusive. Javascript必须不引人注目。

Now, the problem arises, that it doesn't give the value out. 现在出现了问题,那就是它没有给出价值。

When I do this locally, answer has a value of NaN , and if you hit Submit it stays that way, BUT, if you press the back button, you see the actual result. 当我在本地执行此操作时, answer的值为NaN ,如果您单击“ Submit它将保持这种状态,但是,如果您按“后退”按钮,则会看到实际结果。

In the JSFiddle, much is not shown, except for the fact that it simply doesn't work. 在JSFiddle中,除了它根本不起作用外,没有显示很多内容。

Please tell me, is it even possible to make an unobtrusive calculator? 请告诉我,是否有可能制作一个不引人注目的计算器? How? 怎么样?

(PS. I was taking a bit of help from sciencebuddies , just to see basic syntax and stuff, but I found it can't be done without code being obtrusive) 附言 。我从sciencebuddies那里获得了一些帮助,只是为了了解基本的语法和内容,但是我发现如果没有代码的强制性就无法做到)

I realize you're probably just getting started and don't know what to include, remove, and whatnot. 我知道您可能才刚刚起步,不知道要包括,删除和包含哪些内容。 But, good advice here, clearly label your elements so you can understand them, and pare it down to the smallest possible code you need for it to work (even less, so you can build it up). 但是,在这里,好的建议是清楚地标记您的元素,以便您可以理解它们,并将其缩减为工作所需的最小代码(甚至更少,因此可以进行构建)。

Here is your code reworked: 这是修改后的代码:

HTML HTML

<div>
    <input type="text" id="multiplicand" value="4">
    <input type="text" id="multiplier" value="10">
    <button type="button" id="multiply">Multiply</button>
</div>
<p id="result">
    The product is: <span id="product">&nbsp;</span>
</p>

Javascript 使用Javascript

window.onload = function(){
    var button = el('multiply'),
        multiplicand = el('multiplicand'),
        multiplier = el('multiplier'),
        product = el('product');

    function el(id) {
        return document.getElementById(id);
    };

    function multiply() {
        var x = parseFloat(multiplicand.value) || 0,
            y = parseFloat(multiplier.value) || 0;

        product.innerHTML = x * y;
    }

    button.onclick = multiply;
};

http://jsfiddle.net/userdude/EptAN/6/ http://jsfiddle.net/userdude/EptAN/6/

A slightly more sophisticated approach, with add/subtract/multiply/divide: 稍微复杂一点的方法,加/减/乘/除:

http://jsfiddle.net/userdude/EptAN/9/ http://jsfiddle.net/userdude/EptAN/9/

You have to change the submit button so that it doesn't submit the form. 您必须更改“提交”按钮,以便它不提交表单。 Right now clicking "Submit" causes the form submits to the same page which involves a page reload. 现在单击“提交”将导致表单提交到同一页面,这涉及页面重新加载。

Change the <input type="submit" id="submitt"> to <button type=button> and it should work. <input type="submit" id="submitt">更改为<button type=button> ,它应该可以工作。

You can probably do without the <form> element in the first place. 首先,您可能不需要<form>元素。 That'll stop clicking enter in your text input from reloading the page. 这样就不会在重新输入页面时单击文本输入中的Enter键。

Your example has a couple of problems: 您的示例有两个问题:

  1. The form still submits. 该表格仍然提交。 After the JS changes the value, the submit will cause the page to reload, and that work you've done setting the answer value is wasted. 在JS更改值之后,提交将导致页面重新加载,并且浪费了您完成设置答案值的工作。
  2. You're trying to do this stuff right away. 您正在尝试立即执行此操作。 In the header, none of the body has been parsed yet (and thus, the form elements don't even exist). 在标头中,尚未解析任何主体(因此,表单元素甚至不存在)。 You'll want to wait til the page is loaded. 您需要等待直到页面加载完毕。
  3. The script hijacks window.onload . 该脚本劫持了window.onload If you don't have any other scripts on the page, that's fine...but the whole point of unobtrusive JS (IMO) is that nothing breaks whether the script is there or not. 如果您的页面上没有其他脚本,那很好...但是不引人注意的JS(IMO)的要点是,无论该脚本是否存在,都不会中断。

Fixed, we have something kinda like: 固定,我们有点像:

// Wrap this onload in an IIFE that we pass the old onload to, so we can
// let it run too (rather than just replacing it)
(function(old_onload) {

  // attach this code to onload, so it'll run after everything exists
  window.onload = function(event) {

    // run the previous onload
    if (old_onload) old_onload.call(window, event);

    document.getElementById('Xintox').onsubmit = function() {
      var multiplier = +this.multiplier.value;
      var multiplicand = +this.multiplicand.value;
      this.answer.value = multiplier * multiplicand;
      return false;  // keep the form from submitting
    };
  };​
})(window.onload);

Note i'm attaching the meat code to the form, rather than the button, because hitting Enter in either of the factor boxes will trigger a submit as well. 请注意,我将肉类代码附加到表单而不是按钮上,因为在两个因子框中的任意一个中按Enter也会触发提交。 You could still attach to the button if you wanted, and just add a submit handler that returns false. 如果需要,您仍然可以附加到按钮,只需添加一个返回false的提交处理程序。 But IMO it's better this way -- that way the form works just the same with JS as without (assuming the script on the server fills in the boxes appropriately), except it won't require a round trip to the server. 但是IMO最好采用这种方式-那样,表单就可以与JS一样工作,而无需使用JS(假设服务器上的脚本适当地填写了方框),只是不需要往返服务器。

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

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