gpt4 book ai didi

Javascript,保存 onclick 中的值并将以前的值保存在数组中

转载 作者:行者123 更新时间:2023-12-03 04:41:30 25 4
gpt4 key购买 nike

我试图保存从“onclick”检索到的值,并在单击按钮时将之前从“onclick”检索到的值保存在不同的数组中。

但似乎当使用“for 循环”时,新检索到的值会覆盖以前检索到的数据,即使这些值单独保存在不同的数组中。

我现在很困惑,有人知道为什么吗?

(如果您点击“刷新”按钮,您可以看到保存的当前值。)

var firstValue = [];
var preValue = [];



function returneD(a){

preValue = firstValue;
console.log("returned! preValue: "+preValue);

for (var i = 0; i < 1; i++) {
firstValue[i] = a;
console.log("returned! firstValue: "+firstValue);
}
}


function refresh1(){
console.log("preValue: "+preValue);
console.log("firstValue: "+firstValue);
}
<!DOCTYPE html>
<html>
<head>
<script src="jstest.js"></script>
</head>
<body id="thebody">

<button id="1" onclick="returneD(this.id)">O N E</button>
<button id="2" onclick="returneD(this.id)">T W O</button>
<button id="3" onclick="returneD(this.id)">T H R E E</button>
<button id="4" onclick="returneD(this.id)">F O U R</button>
<br>
<button onclick="refresh1()">refresh</button>

</body>
</html>

最佳答案

请引用此代码将起作用,

firstValue 是已经存储值的数组,之后会将旧值分配给 preValue 数组。

var firstValue = [];
var preValue = [];



function returneD(a){

preValue = a;
console.log("returned! preValue: "+preValue);

for (var i = 0; i < 1; i++) {
firstValue[i] = a;
console.log("returned! firstValue: "+firstValue);
}
}


function refresh1(){
console.log("preValue: "+preValue);
console.log("firstValue: "+firstValue);
}
<!DOCTYPE html>
<html>
<head>
<script src="jstest.js"></script>
</head>
<body id="thebody">

<button id="1" onclick="returneD(this.id)">O N E</button>
<button id="2" onclick="returneD(this.id)">T W O</button>
<button id="3" onclick="returneD(this.id)">T H R E E</button>
<button id="4" onclick="returneD(this.id)">F O U R</button>
<br>
<button onclick="refresh1()">refresh</button>

</body>
</html>

关于Javascript,保存 onclick 中的值并将以前的值保存在数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43069288/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com