【问题标题】:Filling array on event and access it outside the event function handler在事件上填充数组并在事件函数处理程序之外访问它
【发布时间】:2016-01-07 15:08:37
【问题描述】:

我正在尝试用按钮的值填充事件(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

我知道为什么这不起作用(这是因为我在事件处理函数中做了所有事情),但我不知道如何做我想做的事情。

有什么建议吗?

【问题讨论】:

  • 为什么要使用函数添加到数组中?它已经是一个函数了......只需将ret = add(n, val); 替换为n.push(val),你应该没有问题。
  • 这只是尝试存储值以在代码的另一部分重用它,因为这是我需要做的。只是替换不起作用,用户 dsh 解释了原因。
  • jup,我错过了,但 dsh 得到了一个不错的支持。

标签: javascript arrays dom events dom-events


【解决方案1】:

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

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;
    }
});

【讨论】:

  • 事实上这并不能解决我的问题。有了这个解决方案,我可以在 div 中看到数组的内容。但我需要在事件处理函数之外,在代码的其他部分使用数组来执行其他操作,例如将其传递给另一个函数、提取值等。
  • 可以在函数外使用,传递给函数等等。你不能做的是获得尚未发生的事件的价值!那么,您需要让您的事件处理程序调用某个函数以使更多的事情发生在点击事件之后。因此,如果您需要更多有关设计事件驱动/异步代码的指导,请填写更多代码。
  • 好的@dsh,我明白了。这一切都是为了让事情发生点击事件发生之后。谢谢。
猜你喜欢
  • 2019-04-26
  • 1970-01-01
  • 2010-12-06
  • 1970-01-01
  • 2021-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多