在事件上填充数组,并在事件函数处理程序外部访问它

Filling array on event and access it outside the event function handler

本文关键字:事件 程序 外部 访问 处理 填充 数组 函数      更新时间:2023-09-26

我试图用按钮的值填充事件(onclick)上的数组(将有不同的按钮具有不同的值,这就是为什么我使用数组),我希望能够访问事件处理程序函数之外的数组。这就是我到目前为止所尝试的,但我只是不知道如何访问事件处理程序函数之外的数组。

HTML:

<button value="5"> button </button>
<div> The value is: <span id="res"></span></div>

这里是脚本:

var n = [];
var val;
var ret;
function add(arr,val) {
arr.push(val); 
return val;
} 
document.body.addEventListener("click", function(event) {
    if (event.target.nodeName == "BUTTON") {
        val = event.target.value;
        ret = add(n, val); 
        console.log(n);      //these console.log are tests
        console.log(ret);
    } 
 console.log(ret);    //also this
});
//need to access the array here
console.log(n);    //obv doesn't work
console.log(ret);  //same
document.getElementById("res").innerHTML = ret;  //it remains undefined, obv

我知道为什么这不起作用(这是因为我在事件处理程序函数内做所有的事情),但我不能弄清楚如何做我想做的事情。

有什么建议吗?

您需要在回调中执行您想要执行的操作,而不是在此之前。原因是事件处理程序中的任何代码都不会在事件发生之前运行。仅仅声明变量并不会改变执行的顺序。
所以你需要输入

document.getElementById("res").innerHTML = ret;

在你的事件处理函数中。

更新(和简化)代码:

var n = [];
document.body.addEventListener("click", function(event) {
    if (event.target.nodeName == "BUTTON") {
        var val = event.target.value;
        n.push(val);
        console.log(n);      //these console.log are tests
        console.log(ret);
        document.getElementById("res").innerHTML = val;
    }
});