使用jquery制作计算器

Previously, I showed you how to use CSS border-radius property to create the following calculator. Now I will show you how to use jQuery to implement the functionality of the calculator.

之前,我向您展示了如何使用CSS border-radius属性创建以下计算器 。 现在,我将向您展示如何使用jQuery来实现计算器的功能。

添加jQuery (Adding jQuery)

We will be using jQuery in this project to respond to events when a user clicks on a button. We need to add the jQuery library to our application. I will use the cdnjs CDN library to add jQuery.

我们将在该项目中使用jQuery来响应用户单击按钮时的事件。 我们需要将jQuery库添加到我们的应用程序中。 我将使用cdnjs CDN库添加jQuery。

At the bottom of my index.html file, I will add the following script tag:

在index.html文件的底部,我将添加以下脚本标记:

<script src=”https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

处理运算符与数字按钮 (Handling operator vs number buttons)

Before writing my code, I decided to brainstorm how I would handle the functionality behind the calculator. I divide the buttons on the calculator into two groups: operator and number.

在编写代码之前,我决定集思广益,如何处理计算器背后的功能。 我将计算器上的按钮分为两组: 运算符数字

A number button would correspond to the numbers 0–9. All other buttons are operators.

一个数字按钮将对应于数字0–9。 所有其他按钮均为运算符。

我们运营的全局变量 (Global variables for our operation)

The next step is to determine how may global variables we will need. The global variables will hold the functionality of our calculator. For example, a user can enter the following sequence:

下一步是确定我们将如何需要全局变量。 全局变量将保留我们计算器的功能。 例如,用户可以输入以下顺序:

2 + 3 = 5

Likewise, a user can enter this much longer sequence:

同样,用户可以输入更长的序列:

2 + 3 * 4 / 5 - 6 = -2

When considering global variables initially, we might consider creating a new variable every time the user presses a key. This would not be very efficient. We would have to keep track of who knows how many variables as the user presses keys.

最初考虑全局变量时,我们可能会考虑在用户每次按键时创建一个新变量。 这将不是很有效。 我们必须跟踪谁知道用户按下按键时有多少个变量。

To improve on this, we can simplify things to only need four global variables:

为了对此进行改进,我们可以简化事情,只需要四个全局变量:

  • num1num1
  • num2num2
  • operator算子
  • total总

Let me show you how this works. The first number the user presses is stored in variable num1. The operator (i.e. +, — , *, / or enter) is stored in the operator. The next number entered is stored in variable 2. Once the second operator is entered, the total is calculated. The total is stored in the variable total.

让我告诉你这是如何工作的。 用户按下的第一个数字存储在变量num1中。 运算符(即+,-,*,/或enter)存储在运算符中。 输入的下一个数字存储在变量2中。输入第二个运算符后,将计算总数。 总数存储在变量总数中。

A logical question would be what do you do with the third or fourth number that a user enters? The simple answer is that we reuse num1 and num2.

一个合理的问题是您将如何处理用户输入的第三个或第四个数字? 简单的答案是我们重用num1和num2。

Once the total has been calculated, we can replace the value in num1 with the total. We would then need to empty out the operator and num2 variables. Let’s walk through this with our second example from above:

一旦计算出总数,我们就可以将num1中的值替换为总数。 然后,我们需要清空运算符和num2变量。 让我们从上面的第二个示例开始学习:

2 + 3 * 4 / 5 - 6 = -2// num1 is assigned value of 2// operator is assigned value of +// num2 is assigned value of 3// total is assigned the value of 5// num1 is assigned the value of 5// num2 and operator are cleared// operator is assigned value of *// num2 is assigned value of 4// total is assigned value of 20// num1 is assigned value of 20// num2 and operator are cleared// operator is stored value of /// num2 is assigned value of 5// total is assigned value of 4// num1 is assigned value of 4// num2 and operator are cleared// operator is assigned value of -// num2 is assigned value of 6// total is assigned value of -2// num1 is assigned value of -2// num2 and operator are cleared// operator is assigned value of =

Now you see that we can handle every possible combination of buttons pressed by the user by using these 4 variables.

现在,您看到我们可以使用这4个变量来处理用户按下的按钮的所有可能组合。

获取用户按下的键 (Getting the key the user pressed)

Now that we have walked through our logic, we need to start the process of handling the key the user pressed. At the bottom of my index.html file, I will create a script tag that will hold my code.

现在我们已经遍历了逻辑,我们需要开始处理用户按下的键的过程。 在index.html文件的底部,我将创建一个脚本标记,该标记将保存我的代码。

The first step is to get the key that a user pressed. Here is a snippet of my index.html file that shows all the buttons on one row of the calculator:

第一步是获取用户按下的键。 这是我的index.html文件的片段,其中显示了计算器的一行上的所有按钮:

<div class="flex-row">    <button class="calc-btn">1</button>    <button class="calc-btn">2</button>    <button class="calc-btn">3</button>    <button class="calc-btn">+</button></div>

Every button, whether it is a number or an operator, is defined using a <button><;/button> element. We can use this to catch when a user clicks on a button.

每个按钮(无论是数字还是运算符)均使用<button>< ; / button>元素定义。 我们可以使用它来捕获用户单击按钮时的情况。

In jQuery, you can have a button click function. When a button is clicked, the function is passed an event object. The event.target will contain the button that was clicked. I can get the value of the button by using the innerHTML property.

在jQuery中,您可以具有按钮单击功能。 单击按钮时,该函数将传递一个事件对象。 event.target将包含已单击的按钮。 我可以通过使用innerHTML属性来获取按钮的值。

Here is the code that will console.log the button that a user clicks.

这是将控制台记录用户单击按钮的代码。

<script>$(document).ready(function() {    $('button').on('click', function(e) {        console.log('e', e.target.innerHTML);    });});</script>

Now if you test the code, you will see the value of the key that you press. This works for every button in the calculator.

现在,如果您测试代码,您将看到您按下的键的值。 这适用于计算器中的每个按钮。

创建我们的全局变量 (Creating our global variables)

Now that we have the ability to determine what key was pressed, we need to start storing them in our global variables. I am going to create my four global variables:

现在我们可以确定按下了什么键,我们需要开始将它们存储在全局变量中。 我将创建四个全局变量:

let num1 = '';let num2 = '';let operator = '';let total = '';

单击时的处理按钮 (Handling button when clicked)

When a user clicks a button, they will be clicking on a number or an operator. For that reason I am going to create two functions:

当用户单击一个按钮时,他们将单击一个数字或一个运算符。 因此,我将创建两个函数:

function handleNumber(num) {    // code goes here}
function handleOperator(oper) {    // code goes here}

In my button click function earlier, I can replace the console.log with a call to the appropriate function. To determine whether a button or operator was clicked, I can compare e.target.innerHTML to see if it is between 0 and 9. If it is, the user clicked a number. If not, the user clicked an operator.

在前面的按钮单击功能中,我可以使用对适当功能的调用来替换console.log。 要确定是否单击了按钮或操作符,我可以比较e.target.innerHTML以查看它是否在0到9之间。如果是,则用户单击一个数字。 如果不是,则用户单击一个运算符。

Here is my initial step to test to make sure I can tell which button was clicked:

这是我测试的第一步,以确保我可以知道单击了哪个按钮:

$(document).ready(function() {    $('button').on('click', function(e) {        let btn = e.target.innerHTML;        if (btn >= '0' && btn <= '9') {            console.log('number');        } else {            console.log('operator');        }    });});

Once I am satisfied that I am identifying each button clicked, I can replace the console.log with a call to the appropriate function:

一旦确定要确定单击的每个按钮,就可以用对适当函数的调用替换console.log:

$(document).ready(function() {    $('button').on('click', function(e) {        let btn = e.target.innerHTML;        if (btn >= '0' && btn <= '9') {            handleNumber(btn);        } else {            handleOperator(btn);        }    });});

处理数字按钮 (Handling number buttons)

When a user presses a number, it will be assigned to either num1 or num2 variable. num1 is assigned value of ''. We can use this to determine what variable to assign the number. If num1 is empty then we assign the number to it. Otherwise, we assign it to num2.

当用户按下数字时,它将被分配给num1或num2变量。 num1被赋值为'' 。 我们可以使用它来确定要分配数字的变量。 如果num1为空,则我们为其分配编号。 否则,我们将其分配给num2。

Here is what my handleNumber function looks like:

这是我的handleNumber函数的样子:

function handleNumber(num) {    if (num1 === '') {        num1 = num;    } else {        num2 = num;    }}

处理操作员按钮 (Handling operator buttons)

Our function to handle when an operator button is pressed is very simple. All we need to do is to assign the value to our operator variable.

我们在按下操作员按钮时的功能非常简单。 我们要做的就是将值分配给我们的运算符变量。

Here is what my handleOperator function looks like:

这是我的handleOperator函数的样子:

function handleOperator(oper) {    operator = oper;}

显示按钮 (Displaying Buttons)

The next step is to actually display the button pressed to the user. If you check out the functionality of the calculator on your phone, you will notice it only displays numbers. If a user presses the + key, it is not displayed.

下一步是实际显示按下给用户的按钮。 如果您在手机上签出计算器的功能,您会发现它仅显示数字。 如果用户按+键,则不会显示。

In our index.html file, we have a div with a class of 'calc-result-input' that displays our input. We will use this to display numbers to our users.

在我们的index.html文件中,我们有一个div,其中包含'calc-result-input' ,用于显示我们的输入。 我们将使用它来向我们的用户显示数字。

Since we have separated out our calculator activity into functions, we will create a function to display the button.

由于我们已将计算器活动划分为函数,因此我们将创建一个函数来显示按钮。

Here is what my displayButton function looks like:

这是我的displayButton函数的样子:

function displayButton(btn) {    $('.calc-result-input').text(btn);}

Since we only update the display when the user presses a number, we can call the displayButton function from within the handleNumber function.

因为我们仅在用户按下数字时更新显示,所以我们可以从displayButton函数中调用handleNumber函数。

Here is what my handleNumber function looks like now:

这是我的handleNumber函数现在的样子:

function handleNumber(num) {    if (num1 === '') {        num1 = num;    } else {        num2 = num;    }    displayButton(num);}

处理总计 (Handling totals)

The next step is to calculate a total. A total is only calculated after a user presses an operator after having a value assigned to num1 and num2.

下一步是计算总数。 只有在用户将值分配给num1 num2之后按下操作员之后,才计算总计。

For example, if the user enters:

例如,如果用户输入:

2 + 3 =

We want to sum num1 and num2 and display the total.

我们要对num1和num2求和并显示总数。

If the user enters:

如果用户输入:

2 - 1 =

We want to subtract num2 from num1 and display the total.

我们要从num1中减去num2并显示总数。

We create a handleTotal function to handle this. This function will create a total based on the operator pressed. Since there are multiple operators that can be pressed, we will use a case statement to handle them.

我们创建一个handleTotal函数来处理此问题。 此功能将根据所按下的操作员创建总计。 由于可以按下多个运算符,因此我们将使用case语句来处理它们。

For simplicity’s sake, I am only going to show the code to handle when the user clicks the + operator button.

为简单起见,我将仅显示当用户单击+操作符按钮时要处理的代码。

Here is the handleTotal function:

这是handleTotal函数:

function handleTotal() {    switch (operator) {        case '+':            total = +num1 + +num2;            displayButton(total);            break;    }}

将字符串转换为数字进行计算 (Converting String to Number for calculation)

When we get the innerHTML of the button that is pressed, we get a string value. To sum two variables, they need to be converted to a number. There is a shorthand notation in JavaScript that will convert a string to a number by prefixing the variable with a + sign. You can see where I am doing this conversion on this line:

当我们获得按下的按钮的innerHTML时,我们得到一个字符串值。 要对两个变量求和,需要将它们转换为数字。 JavaScript中有一种简写的表示法,它将通过在变量前面加上+号来将字符串转换为数字。 您可以在此行上看​​到我在哪里进行此转换:

total = +num1 + +num2;

何时调用handleTotal函数 (When to call handleTotal function)

Now that we have a function to calculate the total, we need to call it at the appropriate time. We only calculate total after a user enters their second operator.

现在我们有了一个计算总数的函数,我们需要在适当的时候调用它。 我们仅在用户输入第二个运算符之后才计算总计。

To handle this we will need to make a change to our existing handleOperator function. Previously, we were assigning the operator variable the value of the operator button the user clicked. Now we need to know if this is the first operator the user has clicked or not. We don’t calculate a total when the user clicks on the first operator.

为了解决这个问题,我们需要对现有的handleOperator函数进行更改。 以前,我们为操作员变量分配了用户单击的操作员按钮的值。 现在,我们需要知道这是否是用户单击的第一个操作员。 用户单击第一个运算符时,我们不计算总数。

To account for this, we can check to see if the operator variable has a value of ''. If so, this is the first operator. If operator has a value, then we will want to calculate a total.

为了解决这个问题,我们可以检查,看看是否操作变量的值'' 。 如果是这样,这是第一个运算符。 如果运算符具有值,那么我们将要计算总数。

Here is what the handleOperator() function looks like now:

这是handleOperator()函数现在的样子:

function handleOperator(oper) {    if (operator === '') {        operator = oper;    } else {        handleTotal();        operator = oper;    }             }

将脚本移至app.js文件 (Moving Script to app.js file)

Currently our HTML and JavaScript code are all contained in the index.html file. We want to split out the logic into a separate file. I create a new file called app.js.

当前,我们HTML和JavaScript代码都包含在index.html文件中。 我们想将逻辑拆分成一个单独的文件。 我创建一个名为app.js的新文件。

I copy the entire contents of the <script> tag into this file. I delete the opening &lt;script> tag and closing </script> tag in my index.html file.

我将<scri pt>标记的全部内容复制到此文件中。 我删除了index.html文件中的优化ening &l script>标签and closi </ script>标签。

The last thing we need to do is to tell our index.html file where our scripts are. We do this by adding this line below the <script> tag that loads jQuery at the bottom of the index.html file:

我们需要做的最后一件事是告诉我们的index.html文件我们的脚本在哪里。 为此,我们在<scri pt>标签下面添加了以下行,该标签将jQuery加载到index.html文件的底部:

<script src="app.js"></script>

最终文件 (Final Files)

I now have these three files:

我现在有以下三个文件:

  • index.htmlindex.html
  • app.jsapp.js
  • style.cssstyle.css

The index.html file is used to display the calculator to the user on the web page.

index.html文件用于在网页上向用户显示计算器。

The style.css is used to style my calculator. Please review my previous article that talks about using the CSS border-radius property to style the calculator.

style.css用于为计算器设置样式。 请查看我以前的文章,该文章讨论如何使用CSS border-radius属性设置计算器的样式。

The app.js file contains the logic behind the calculator.

app.js文件包含计算器背后的逻辑。

Here is what my app.js file looks like:

这是我的app.js文件的样子:

let num1 = '';let num2 = '';let operator = '';let total = '';
$(document).ready(function() {    $('button').on('click', function(e) {        let btn = e.target.innerHTML;        if (btn >= '0' && btn <= '9') {            handleNumber(btn);        } else {            handleOperator(btn);        }    });});
function handleNumber(num) {    if (num1 === '') {        num1 = num;    } else {        num2 = num;    }    displayButton(num);}
function handleOperator(oper) {    if (operator === '') {        operator = oper;    } else {        handleTotal();        operator = oper;    }}
function handleTotal() {    switch (operator) {        case '+':            total = +num1 + +num2;            displayButton(total);            break;        case '-':            total = +num1 - +num2;            displayButton(total);            break;        case '/':            total = +num1 / +num2;            displayButton(total);            break;        case 'X':            total = +num1 * +num2;            displayButton(total);            break;    }    updateVariables();}
function displayButton(btn) {    $('.calc-result-input').text(btn);}
function updateVariables() {    num1 = total;    num2 = '';}

摘要 (Summary)

Our calculator works, but only if the user clicks the + operator. You can add to the functionality in the handleTotal function to account for all operators. I have all the functionality in my repo which you can find here.

我们的计算器可以工作,但前提是用户单击+运算符。 您可以在handleTotal函数中添加功能以说明所有运算符。 我的仓库中有所有功能,您可以在此处找到 。

进一步阅读 (Further Readings)

Breadth First Search in JavaScript — The two most common methods of searching a graph or a tree are depth first search and breadth first search. This story shows you how to use a breadth first search of a graph or a tree.

JavaScript中的广度优先搜索 -搜索图形或树的两种最常见的方法是深度优先搜索和广度优先搜索。 这个故事向您展示如何使用图形或树的广度优先搜索。

Instantiation Patterns in JavaScript — Instantiation patterns are ways to create something in JavaScript. JavaScript provides four different methods to create objects. Learn how to create all four in this article.

JavaScript中的实例化模式-实例化模式是在JavaScript中创建内容的方法。 JavaScript提供了四种创建对象的不同方法。 在本文中学习如何创建所有四个。

Using Node.js & Express.js to save data to MongoDB Database — The MEAN stack is used to describe development using MongoDB, Express.js, Angular.jS and Node.js. In this tutorial I will show you how to use Express.js, Node.js and MongoDB.js. We will be creating a very simple Node application, that will allow users to input data that they want to store in a MongoDB database.

使用Node.js和Express.js将数据保存到MongoDB数据库中 -MEAN堆栈用于描述使用MongoDB,Express.js,Angular.jS和Node.js的开发。 在本教程中,我将向您展示如何使用Express.js,Node.js和MongoDB.js。 我们将创建一个非常简单的Node应用程序,该应用程序将允许用户输入要存储在MongoDB数据库中的数据。

翻译自: https://www.freecodecamp.org/news/programming-a-calculator-8263966a8019/

使用jquery制作计算器

使用jquery制作计算器_如何使用jQuery对计算器进行编程相关推荐

  1. cdn jquery怎么没有提示_第一个jQuery程序

    1.配置jQuery环境 1.1获取jQuery最新版本 进入jQuery的官方网址 http://jquery.com ,下载最新的jQuery库. 1.2 jQuery库类型说明 目前jQuery ...

  2. jquery开发插件_如何开发jQuery插件

    jquery开发插件 We have gone through different jQuery event methods, jQuery effects and animations in the ...

  3. 矩阵化简计算器_论一台图形计算器,如何拯救你的SAT2数学

    为了SAT,SAT2以及AP考试,很多同学都准备了TI-84,TI-Nspire以及各种各样的图形计算器来应对考试.这些计算器最大的共同点,就是贵,但是贵一定有贵的道理.那么在整场考试中,你有多少题目 ...

  4. python 写一个计算器_用 Python 写个计算器

    首页 专栏 python 文章详情 0 用 Python 写个计算器 Python小二 发布于 56 分钟前 我们常见的计算辅助工具有两种,一种是古人发明的算盘,另一种就是我们现代人发明的计算器,与算 ...

  5. 安全期在线计算计算机,【排卵期查询计算器_排卵期查询计算器专题】- 天鹅到家...

    很多要想比较技术专业且精确地预测分析自身的排卵期的女性.要想怀孕或避开怀孕的女性,或是要想根据对排卵期的预测分析,根据排卵期時间的不一,对生理学病症做出一些预防的女性,能够运用女性排卵期计算器.女性排 ...

  6. python制作计算机程序_用 Python 开发实用程序 – 计算器

    一段时间前,自己制作了一个库 "sui-math".这其实是 math 的翻版.做完后,我又想到,python 既然可以轻易的完成任何的数学计算,何不用 python 开发一个小程 ...

  7. jquery 图像滑块_如何使用jQuery构建图像滑块

    jquery 图像滑块 This tutorial will walk you through building an image slider using the jQuery library. 本 ...

  8. java_web网页版计算器_简单的Web版计算器 - Mr_DeFore的个人空间 - OSCHINA - 中文开源技术交流社区...

    先完成html部分的代码: html> My Calculator My Calculator 0 7 8 9 4 5 6 1 2 3 0 . / 清零 * 退格 - = + 完成之后有这样的效 ...

  9. Java正则表达式实现计算器_用java编写win7计算器

    展开全部 参考代码:62616964757a686964616fe78988e69d8331333337393635import java.awt.*; import java.awt.event.* ...

最新文章

  1. 深度学习到底有哪些卷积?
  2. ansible-playbook之条件判断
  3. Vim编程之:tags,cscope,taglist
  4. 关于mysql优化_MYSQL---关于MYSQL优化
  5. linux命令chown和chmod什么区别
  6. 系统会自带java吗_使用eclipse自带制作帮助系统
  7. 开源 20 年,为何程序员对闭源越来越厌恶?
  8. Wekan 部署文档
  9. java 美元符号_有什么区别 . (点)和$(美元符号)?
  10. 现身说法 程序员 35 岁后的出路
  11. 最新安卓JAVA模拟器_安卓java模拟器完美版下载-安卓java模拟器直装最新版下载v1.4.6 - 欧普软件园...
  12. 计算机网络英语作文150字,微信投票的英语,写一篇关于网络投票看法的英语作文150字左右...
  13. Android App专项测试-压力测试篇
  14. 怎么快速做一个excel手机报表?
  15. 120行代码爬取电子书网站
  16. 图像和图形(位图与矢量图)
  17. 计算机录制语音所必需的硬件,录音电脑配置方面的硬件要求
  18. 替换掉NO_OS逻辑和代码中的SPI部分
  19. 实体类转换DTO的方式
  20. 画师绘制《进击的巨人》电影版海报 堪比好莱坞- Micro Reading

热门文章

  1. python类与对象 封装继承与多态 0308
  2. dj鲜生-01-新建项目-配置数据库
  3. 查询某个条件在一个区间内的数据
  4. linux通过bg后台执行作业
  5. hdu 5616 Jam's balance(dp 正反01背包)
  6. Mysql开启远程连接方法
  7. cocos2d-x 3.0rc开发指南:Windows下Android环境搭建
  8. Cocos2d-x win7 + vs2010 配置图文详解(转)
  9. Android美工坊--一个QQ登录验证的小例子
  10. 结合 live-reload 实现自动刷新