【问题标题】:get the variables inside the event at the time outside the listening event在监听事件外的时间获取事件内的变量
【发布时间】:2019-02-22 11:39:43
【问题描述】:

考虑下面的函数‍seletcolor()

function seletcolor() {
    var button = document.querySelector("button");
    var a = 1;
    button.onclick = function (e) {
        a = a++;
    };
    console.log(a);
}

单击按钮后,我想在事件外部打印出变量a 的值。

【问题讨论】:

标签: javascript events button


【解决方案1】:

由于您想在他们单击时打印值,因此您需要将 console.log 调用放在 onclick 函数中。

function seletcolor() {
    var button = document.querySelector("button");
    var a = 1;
    button.onclick = function (e) {
        a++;
        console.log(a);
    };
}

另外,要增加一个变量,它只是a++。这会执行分配,您不需要将其重新分配(这实际上撤消了增量,因为 a++ 返回旧值)。

【讨论】:

    猜你喜欢
    • 2015-07-15
    • 1970-01-01
    • 2018-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多