Zuvor habe ich Ihnen gezeigt, wie Sie mit der CSS-Eigenschaft "Rahmenradius" den folgenden Taschenrechner erstellen. Jetzt werde ich Ihnen zeigen, wie Sie mit jQuery die Funktionalität des Rechners implementieren.

JQuery hinzufügen
In diesem Projekt wird jQuery verwendet, um auf Ereignisse zu reagieren, wenn ein Benutzer auf eine Schaltfläche klickt. Wir müssen die jQuery-Bibliothek zu unserer Anwendung hinzufügen. Ich werde die CDN-Bibliothek cdnjs verwenden, um jQuery hinzuzufügen.
Am Ende meiner index.html-Datei füge ich das folgende Skript-Tag hinzu:
Handling Operator vs Zifferntasten
Bevor ich meinen Code schrieb, beschloss ich, mir Gedanken darüber zu machen, wie ich mit der Funktionalität hinter dem Taschenrechner umgehen würde. Ich teile die Tasten am Taschenrechner in zwei Gruppen ein: Operator und Nummer .
Eine Zifferntaste würde den Ziffern 0–9 entsprechen. Alle anderen Schaltflächen sind Operatoren.
Globale Variablen für unseren Betrieb
Der nächste Schritt besteht darin, zu bestimmen, wie viele globale Variablen wir benötigen. Die globalen Variablen enthalten die Funktionalität unseres Rechners. Ein Benutzer kann beispielsweise die folgende Sequenz eingeben:
2 + 3 = 5
Ebenso kann ein Benutzer diese viel längere Sequenz eingeben:
2 + 3 * 4 / 5 - 6 = -2
Wenn Sie anfänglich globale Variablen berücksichtigen, sollten Sie möglicherweise jedes Mal eine neue Variable erstellen, wenn der Benutzer eine Taste drückt. Dies wäre nicht sehr effizient. Wir müssten nachverfolgen, wer wie viele Variablen kennt, wenn der Benutzer Tasten drückt.
Um dies zu verbessern, können wir die Dinge vereinfachen, indem wir nur vier globale Variablen benötigen:
- num1
- num2
- Operator
- gesamt
Lassen Sie mich Ihnen zeigen, wie das funktioniert. Die erste Nummer, die der Benutzer drückt, wird in der Variablen num1 gespeichert. Der Operator (dh +, -, *, / oder Eingabe) wird im Operator gespeichert. Die nächste eingegebene Nummer wird in Variable 2 gespeichert. Sobald der zweite Operator eingegeben wurde, wird die Summe berechnet. Die Summe wird in der variablen Summe gespeichert.
Eine logische Frage wäre, was machen Sie mit der dritten oder vierten Nummer, die ein Benutzer eingibt? Die einfache Antwort ist, dass wir num1 und num2 wiederverwenden.
Sobald die Summe berechnet wurde, können wir den Wert in num1 durch die Summe ersetzen. Wir müssten dann die Variablen operator und num2 leeren. Lassen Sie uns dies mit unserem zweiten Beispiel von oben durchgehen:
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 =
Jetzt sehen Sie, dass wir mit diesen 4 Variablen jede mögliche Kombination von vom Benutzer gedrückten Tasten verarbeiten können.
Den Benutzer die Taste drücken lassen
Nachdem wir unsere Logik durchlaufen haben, müssen wir den Prozess der Handhabung der vom Benutzer gedrückten Taste starten. Am Ende meiner index.html-Datei erstelle ich ein Skript-Tag, das meinen Code enthält.
Der erste Schritt besteht darin, die Taste zu erhalten, die ein Benutzer gedrückt hat. Hier ist ein Ausschnitt aus meiner index.html-Datei, in der alle Schaltflächen in einer Zeile des Rechners angezeigt werden:
1 2 3 +
Jede Schaltfläche, ob es sich um eine Zahl oder einen Operator handelt, wird mit einem <
; / button> -Element definiert. Wir können dies verwenden, um zu erfassen, wenn ein Benutzer auf eine Schaltfläche klickt.
In jQuery können Sie eine Schaltfläche zum Klicken auf eine Schaltfläche verwenden. Wenn Sie auf eine Schaltfläche klicken, wird der Funktion ein Ereignisobjekt übergeben. Das event.target
wird die Schaltfläche enthalten, auf die geklickt wurde. Ich kann den Wert der Schaltfläche mithilfe der innerHTML
Eigenschaft ermitteln.
Hier ist der Code, mit dem console.log die Schaltfläche protokolliert wird, auf die ein Benutzer klickt.
$(document).ready(function() { $('button').on('click', function(e) { console.log('e', e.target.innerHTML); });});
Wenn Sie nun den Code testen, sehen Sie den Wert der Taste, die Sie drücken. Dies funktioniert für jede Schaltfläche im Taschenrechner.
Erstellen unserer globalen Variablen
Nachdem wir nun feststellen können, welche Taste gedrückt wurde, müssen wir sie in unseren globalen Variablen speichern. Ich werde meine vier globalen Variablen erstellen:
let num1 = '';let num2 = '';let operator = '';let total = '';
Schaltfläche "Behandeln" beim Klicken
Wenn ein Benutzer auf eine Schaltfläche klickt, klickt er auf eine Zahl oder einen Operator. Aus diesem Grund werde ich zwei Funktionen erstellen:
function handleNumber(num) { // code goes here}
function handleOperator(oper) { // code goes here}
In meiner früheren Funktion zum Klicken auf eine Schaltfläche kann ich die Datei console.log durch einen Aufruf der entsprechenden Funktion ersetzen. Um festzustellen, ob auf eine Schaltfläche oder einen Operator geklickt wurde, kann ich vergleichen e.target.innerHTML
, ob sie zwischen 0 und 9 liegt. Wenn dies der Fall ist, hat der Benutzer auf eine Zahl geklickt. Wenn nicht, hat der Benutzer auf einen Operator geklickt.
Hier ist mein erster Schritt zum Testen, um sicherzustellen, dass ich feststellen kann, auf welche Schaltfläche geklickt wurde:
$(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'); } });});
Sobald ich zufrieden bin, dass ich jede angeklickte Schaltfläche identifiziere, kann ich das console.log durch einen Aufruf der entsprechenden Funktion ersetzen:
$(document).ready(function() { $('button').on('click', function(e) { let btn = e.target.innerHTML; if (btn >= '0' && btn <= '9') { handleNumber(btn); } else { handleOperator(btn); } });});
Umgang mit Zifferntasten
Wenn ein Benutzer eine Nummer drückt, wird diese entweder der Variablen num1 oder num2 zugewiesen. num1 wird der Wert von zugewiesen ''
. Wir können dies verwenden, um zu bestimmen, welche Variable die Nummer zuweisen soll. Wenn num1 leer ist, weisen wir ihm die Nummer zu. Andernfalls weisen wir es num2 zu.
So sieht meine handleNumber-Funktion aus:
function handleNumber(num) { if (num1 === '') { num1 = num; } else { num2 = num; }}
Bedienung von Bedientasten
Unsere Funktion zum Drücken einer Bedientaste ist sehr einfach. Alles was wir tun müssen, ist den Wert unserer Operatorvariablen zuzuweisen.
So sieht meine handleOperator-Funktion aus:
function handleOperator(oper) { operator = oper;}
Schaltflächen anzeigen
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.
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:
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.
Here is what my handleNumber function looks like now:
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.
For example, if the user enters:
2 + 3 =
We want to sum num1 and num2 and display the total.
If the user enters:
2 - 1 =
We want to subtract num2 from num1 and display the total.
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.
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:
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:
total = +num1 + +num2;
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.
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:
function handleOperator(oper) { if (operator === '') { operator = oper; } else { handleTotal(); operator = oper; } }
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
.
I copy the entire contents of the ening &l
t;script> tag and closi
ng tag in my index.html file.
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
Final Files
Final Files
I now have these three files:
index.html
app.js
style.css
The index.html file is used to display the calculator to the user on the web page.
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.
The app.js file contains the logic behind the calculator.
Here is what my app.js file looks like:
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
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.
Further Readings
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.
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.
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.

Original text