简体   繁体   中英

Why when I call function after another is completed, it calls all previous?

I want to make such as text game based on console. When user writes his name, it should call a function with age input and after age input it should call sex input. But when I write my age, it calls getAge again + next function. After next function it calls getAge + next function + next function. I hope you know, what I mean. How can I fix it? I tried a callback, but it didn't help.

 $(document).ready(function(){ var Player = { username : "", age : null, sex : "", }; function textArea($text){ return $('#textArea').val($('#textArea').val() + $text); }; function clearInput(){ return $('#inputs').val(''); } var functions = { start : function start(){ functions.getUsername(); }, //START GET USERNAME getUsername : function getUserName(callback){ //Hello! Tell me your username! textArea("Vítej! Zadej svou přezdívku!"); $('#inputs').keypress(function (e){ if (e.which == 13){ Player.username = $('#inputs').val(); textArea("\\n" + Player.username + "\\n"); clearInput(); functions.getAge(); } }); }, //END GET USERNAME //START GET AGE getAge : function getAge(){ //Tell me your age! textArea("Zadej svůj věk!"); $('#inputs').keypress(function (e){ if (e.which == 13){ Player.age = $("#inputs").val(); textArea("\\n" + Player.age + "\\n"); clearInput(); functions.getSex(); } }); }, //END GET AGE getSex : function getSex(){ //Tell me your sex: male/female textArea("Zadej pohlaví: muž/žena"); $('#inputs').keypress(function (e){ if (e.which == 13){ Player.sex = $('#inputs').val(); textArea("\\n" + Player.sex + "\\n"); clearInput(); //Another function } }); } }; functions.start(); }); 
 #content>*{ display: block; margin: 0 auto ; } #textArea{ box-shadow: 2px 2px 2px grey; background: black; color: white; } #inputs{ width: 61%; margin-top: 10px; background: black; color: white; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <link rel="stylesheet" type="text/css" href="style.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script> <script src="script.js"></script> </head> <body> <div id="content"> <textarea id="textArea" rows="30" cols="100"></textarea> <input type="text" id="inputs"> </div> </body> </html> 

Each function call adds a keypress listener to your textarea. So after your getAge() call, you have 2 listeners. Therefore, next keypress will call getAge AND getSex . So, one solution would be to remove the previous listener before setting a new one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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