如何在Javascript中从一个函数访问变量到另一个函数?

时间:2013-02-04 04:55:52

标签: javascript html

我有提示对话框,其中包含电子邮件值,需要在另一个函数Email()中传递Email变量。这是我的代码。

function promptMessage() {
    public var Email = prompt("Enter your Email :", "");
}
function Email(){
    alert("Email Address is " +Email); //Email from promptMessage() function 
}

3 个答案:

答案 0 :(得分:3)

怎么样

function promptMessage() {
    return prompt("Enter your Email :", "");
}
function Email(email){
    alert("Email Address is " +email); //Email from promptMessage() function 
}
Email(promptMessage());

答案 1 :(得分:1)

只是声明它在函数范围之外,不要使用函数名作为变量名,这将导致恶梦:

var EmailAddr;

function promptMessage() {
     EmailAddr = prompt("Enter your Email :", "");
}
function Email(){
    alert("Email Address is " +EmailAddr); //Email from promptMessage() function 
}

答案 2 :(得分:0)

由于您在函数内部(在本地范围内)声明了Email变量,因此无法在此函数之外访问它。相反,将其定义为外部像全局var:

var email;
function promptMessage() {
    email = prompt("Enter your Email :", "");
}
function Email(){
    alert("Email Address is " +email); //Email from promptMessage() function 
}