【问题标题】:Why doesn't my function change value of variable? [closed]为什么我的函数不改变变量的值? [关闭]
【发布时间】:2021-10-22 01:21:17
【问题描述】:

当我尝试更改变量的值时遇到问题。

var id = null;
async function getUser() {
    let user = document.getElementById('user').value;
    let passs = document.getElementById('pass').value;

    let res = await eel.login(user, passs)();

    let text = res[0];

    let id_res = res[1];

    if (text == 'Вы успешно авторизовались!') {
        window.location.href = 'index.html';
    } else if (text == 'Неправильное имя пользователя или пароль') {
        alert(text);
    }

    var copy = $.extend( {}, id );
    copy = id_res; // that's my problematic part

    alert(id); // allerting updated variable
}

然后,当我尝试使用 "id" 变量时,它仍然返回 "null"

async function createTask() {
    let task = document.getElementById('need_task').value;

    let result = await eel.create_task(copy, task);
    alert(copy); // got error, that copy is undefined
}

另外,在我的html中,我添加了 document.getElementById('btn').addEventListener('click', getUser);"document.getElementById('but') .addEventListener('click', createTask);" 来激活我的功能。

如您所见,我使用 python eel 库。所以我想,我的错误在于那条鳗鱼。 我会很感激你的任何帮助!

【问题讨论】:

  • var id 声明了一个名为 idnew 变量,它从外部隐藏声明 var id
  • 你能做一个consol.log(res[1])
  • 但是当我在第一个函数中运行“alert(id)”时,值发生了变化
  • Moaud louhichi,是的,当我执行 consol.log(res[1]) 时,我得到了正确的值。
  • 尝试从这行 'var id = id_res;' 中删除关键字 'var'

标签: javascript html function return var


【解决方案1】:

您应该阅读本文以了解 javascript 中的副本:Copy a variable's value into another

var id = null;
async function getUser() {
    let user = document.getElementById('user').value;
    let passs = document.getElementById('pass').value;

    let res = await eel.login(user, passs)();

    let text = res[0];

    let id_res = res[1];

    if (text == 'Вы успешно авторизовались!') {
        window.location.href = 'index.html';
    } else if (text == 'Неправильное имя пользователя или пароль') {
        alert(text);
    }

    id = id_res; // remove var

    alert(id); // will alert updated value.
}

现在不需要更改第二个功能

【讨论】:

  • 我已经阅读了这个信息,但我想没有得到它。阅读后我编辑了我的代码,请看一下。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-08-06
  • 1970-01-01
  • 2013-10-29
  • 1970-01-01
  • 1970-01-01
  • 2022-07-04
  • 1970-01-01
相关资源
最近更新 更多