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

这篇博客介绍了如何使用jQuery为计算器创建功能。首先,通过添加jQuery库来响应按钮点击事件。接着,博主通过四个全局变量(num1, num2, operator, total)来处理运算过程。在用户点击按钮时,通过判断是数字还是运算符来调用相应的处理函数,并将结果显示在屏幕上。文章还涉及如何处理总计、转换字符串为数字进行计算以及何时调用计算总和的函数。最后,将脚本移到独立的app.js文件中,实现了计算器的完整功能。" 121237911,11593901,Redis Stream类型详解与实战,"['数据库', 'redis', '数据结构']
摘要由CSDN通过智能技术生成

使用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:

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

  • num1

    num1
  • num2

    num2
  • 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.html

    index.html
  • app.js

    app.js
  • style.css

    style.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制作计算器

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值