כיצד לתכנת מחשבון עם jQuery

בעבר הראיתי לך כיצד להשתמש במאפיין CSS border-radius ליצירת המחשבון הבא. עכשיו אני אראה לך כיצד להשתמש ב- jQuery כדי ליישם את הפונקציונליות של המחשבון.

הוספת jQuery

נשתמש ב- jQuery בפרויקט זה כדי להגיב לאירועים כאשר משתמש לוחץ על כפתור. עלינו להוסיף את ספריית jQuery ליישום שלנו. אשתמש בספריית CDNjs CDN כדי להוסיף jQuery.

בתחתית קובץ index.html, אוסיף את תג הסקריפט הבא:

טיפול במפעיל מול כפתורי מספר

לפני שכתבתי את הקוד שלי, החלטתי לעשות סיעור מוחות כיצד אתמודד עם הפונקציונליות שמאחורי המחשבון. אני מחלק את הכפתורים על המחשבון לשתי קבוצות: מפעיל ו מספר .

כפתור מספר יתאים למספרים 0–9. כל שאר הכפתורים הם אופרטורים.

משתנים גלובליים לפעולה שלנו

השלב הבא הוא לקבוע עד כמה נצטרך משתנים גלובליים. המשתנים הגלובליים יחזיקו בפונקציונליות של המחשבון שלנו. לדוגמה, משתמש יכול להזין את הרצף הבא:

2 + 3 = 5

כמו כן, משתמש יכול להזין את הרצף הארוך בהרבה:

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

כשבוחנים בתחילה משתנים גלובליים, אנו עשויים לשקול ליצור משתנה חדש בכל פעם שהמשתמש לוחץ על מקש. זה לא יהיה יעיל במיוחד. נצטרך לעקוב אחר מי יודע כמה משתנים כאשר המשתמש לוחץ על המקשים.

כדי לשפר את זה, אנחנו יכולים לפשט דברים שזקוקים רק לארבעה משתנים גלובליים:

  • מספר 1
  • מספר 2
  • מַפעִיל
  • סך הכל

תן לי להראות לך איך זה עובד. המספר הראשון שהמשתמש לוחץ עליו נשמר במשתנה מספר 1. המפעיל (כלומר +, -, *, / או enter) מאוחסן במפעיל. המספר הבא שהוזן נשמר במשתנה 2. ברגע שמזינים את האופרטור השני מחושבים הסכום. הסך הכל נשמר בסך הכל המשתנה.

שאלה הגיונית תהיה מה עושים עם המספר השלישי או הרביעי שמשתמש מזין? התשובה הפשוטה היא שאנחנו עושים שימוש חוזר ב- num1 ו- num2.

לאחר חישוב הסכום, אנו יכולים להחליף את הערך ב- 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 =

כעת אתה רואה שנוכל להתמודד עם כל שילוב אפשרי של לחצנים שנלחץ על ידי המשתמש באמצעות 4 המשתנים הללו.

קבלת המקש שהמשתמש לחץ עליו

כעת לאחר שעברנו את ההיגיון שלנו, עלינו להתחיל בתהליך הטיפול במקש שהמשתמש לחץ עליו. בתחתית קובץ index.html שלי, אני אצור תג סקריפט שיחזיק את הקוד שלי.

הצעד הראשון הוא לקבל את המפתח שמשתמש לחץ עליו. הנה קטע מקובץ index.html שלי המציג את כל הכפתורים בשורה אחת של המחשבון:

 1 2 3 + 

כל כפתור, בין אם זה מספר או אופרטור, מוגדר באמצעות <אלמנט; / button>. אנו יכולים להשתמש בזה בכדי לתפוס כאשר משתמש לוחץ על כפתור.

ב- jQuery, תוכל לבצע פונקציית לחיצה על כפתור. כאשר לוחצים על כפתור, הפונקציה עוברת לאובייקט אירוע. ה- event.targetיכיל את הכפתור עליו לחצו. אני יכול לקבל את ערך הכפתור באמצעות innerHTMLהמאפיין.

הנה הקוד שיינחם את הכפתור שעליו משתמש לוחץ.

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

כעת אם תבדוק את הקוד, תראה את ערך המקש שאתה לוחץ עליו. זה עובד על כל כפתור במחשבון.

יצירת המשתנים הגלובליים שלנו

כעת, כשיש לנו אפשרות לקבוע איזה מקש נלחץ, עלינו להתחיל לאחסן אותם במשתנים הגלובליים שלנו. אני הולך ליצור את ארבעת המשתנים הגלובליים שלי:

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

כפתור הטיפול בלחיצה עליו

כאשר משתמש לוחץ על כפתור, הוא ילחץ על מספר או על מפעיל. מסיבה זו אני הולך ליצור שתי פונקציות:

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

בפונקציית לחיצת הכפתור שלי קודם לכן, אני יכול להחליף את console.log בשיחה לפונקציה המתאימה. כדי לקבוע אם לחצו על כפתור או אופרטור, אני יכול להשוות בין e.target.innerHTMLאם הוא בין 0 ל 9. אם כן, המשתמש לחץ על מספר. אם לא, המשתמש לחץ על מפעיל.

הנה הצעד הראשוני שלי לבדיקה כדי לוודא שאוכל לדעת על איזה כפתור לחצו:

$(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'); } });});

ברגע שאהיה מרוצה שאני מזהה כל לחצן שנלחץ עליו, אוכל להחליף את 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); } });});

טיפול בכפתורי המספרים

כאשר משתמש לוחץ על מספר, הוא יוקצה למשתנה מספר 1 או מספר 2. מספר 1 מוקצה לערך ''. אנו יכולים להשתמש בזה כדי לקבוע איזה משתנה להקצות את המספר. אם מספר 1 ריק אז נקצה לו את המספר. אחרת, אנו מקצים אותו ל- num2.

כך נראית פונקציית ה- handleNumber שלי:

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

טיפול בכפתורי מפעיל

הפונקציה שלנו לטפל כאשר לוחצים על כפתור מפעיל היא פשוטה מאוד. כל שעלינו לעשות הוא להקצות את הערך למשתנה המפעיל שלנו.

כך נראית פונקציית handleOperator שלי:

function handleOperator(oper) { operator = oper;}

הצגת כפתורים

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 pt> tag into this file. I delete the opening &lt;script> tag and closing 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 pt> tag that loads jQuery at the bottom of the index.html file:

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

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

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