我正在尝试在addeventlistner外部访问“ var accInfo”的值,以便可以将此对象用于进一步的编码。我是javascript的初学者,不了解jquery和其他框架,所以请帮我。谢谢

let form1 = document.getElementById('form1');

form1.addEventListener('submit', () => {
    let fname = document.getElementById("defaultRegisterFormFirstName").value
    let lname = document.getElementById("defaultRegisterFormLastName").value
    let email = document.getElementById("defaultRegisterFormEmail").value
    var accInfo = acc(fname, lname,email);
    console.log(accInfo)
    return false
})

function acc(fname,lname, email){
    let accInfo = {fname, lname, email}
    return accInfo;
}

最佳答案

将accInfo定义为全局变量,如下所示:

var accInfo; //leave it undefined for now
form1.addEventListener('submit', () => {
    //...
    accInfo = acc(fname, lname,email);
    //...
})

function acc(fname,lname, email){
    let anotherVariableName = {fname, lname, email}
    return anotherVariableName;
}

//now you can use it outside, but it will be undefined until the event listener is called
console.log(accInfo);


您必须更改功能acc以使其变量具有其他名称

09-25 21:34