簡體   English   中英

為什么當我在另一個函數完成后調用函數時,它又調用了所有先前的函數?

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

我想做基於控制台的文字游戲。 用戶輸入姓名時,應使用年齡輸入功能,而在輸入年齡后,應調用性別輸入。 但是當我寫下年齡時,它將再次調用getAge + next函數。 在next函數之后,它將調用getAge + next函數+ next函數。 我希望你知道我的意思。 我該如何解決? 我嘗試了一個回調,但沒有幫助。

 $(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> 

每個函數調用都會向您的文本區域添加一個keypress監聽器。 因此,在調用getAge()之后,您將擁有2個偵聽器。 因此,下次按鍵將調用getAgegetSex 因此,一種解決方案是在設置新的偵聽器之前刪除先前的偵聽器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM