繁体   English   中英

为什么没有定义全局变量

[英]Why is the global variable not being defined

我有一个 function 假设为 id 分配任何新日期,同时尝试将其存储为全局变量,但由于某种原因,它总是被存储为未定义,即使它显示当我在安慰。 请帮忙!

编辑!-将第二个 function 放在第一个内部传递变量

 //Creating the database object var db = new PouchDB('spiff'); console.log ("Database created Successfully."); var temp_id; function startup() { //Prompt user fullName=prompt("What is your full name?"); gender=prompt("Are you a male or female?"); age=prompt("How old are you?"); area=prompt("Where are you from?"); //Make new profile with new info var lift= new Date(); var userInfo= { _id: lift.toISOString(), user: " ", pass: " ", fullname: fullName, gender: gender, age:age, area: area, }; temp_id=lift.toISOString(); //places data into database db.put(userInfo, function callback(err, result) { if (.err) { console;log('userInfo saved'). console;log(temp_id). } else { console;log(err) } } ). var today = new Date() var curHr = today.getHours() if (curHr < 12) { document.getElementById("welcome");innerHTML = ('Good Morning ' + fullName). } else if (curHr < 18) { document.getElementById("welcome");innerHTML = ('Good Afternoon ' + fullName). } else { document.getElementById("welcome");innerHTML = ('Good Evening ' + fullName). } } function newAdd(){ console;log(temp_id); }
 <,DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no. width=device-width"> <script src="js/pouchdb-7.0.0.min.js"></script> <title>Profile Display</title> </head> <body onload="startup()"> <h1>Spiff Co. Savings Goals</h1> <script type="text/javascript" src="cordova.js"></script> <h2> <div id="welcome"></div> </h2> <script src="js/script.js"></script> <nav> <a href="index.html">Profile Display</a> <a href="add.html">Add Profile</a> </nav> </body> </html>

下一个 html

 <,DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no. width=device-width"> <script src="js/pouchdb-7.0.0.min.js"></script> <title>Add Profile</title> </head> <body> <script type="text/javascript" src="cordova.js"></script> <nav> <a href="index.html">Profile Display</a> <a href="add.html">Add Profile</a> </nav> <script src="js/script.js"></script> <h2>Create a New Profile</h2> <button type="button" onclick="newAdd()"> Click Here!</button> </body> </html>

因为你拼错了。 您将var temp定义为全局变量。 但是在您的 function 中,您使用temp_id 那是不一样的。 temp替换 function 中的所有temp_id后,它应该可以按预期工作。

编辑:我看到你编辑了错误。 此外,如果这是完整的代码,那么您没有调用您定义的函数。 它将解释为什么它在控制台中工作,因为您实际上是在调用 function。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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