gpt4 book ai didi

javascript - 如何将值存储在数组中

转载 作者:行者123 更新时间:2023-11-28 01:43:14 25 4
gpt4 key购买 nike

在下面的代码中,我获取条形码的扫描值。

var scanCode = function () {
window.plugins.barcodeScanner.scan(function(result) {
alert("Scanned Code: " + result.text + ". Format: " + result.format + ". Cancelled: " + result.cancelled);
localStorage.setItem("myvalue1", result.text);
window.location.href = 'page5.html';
var barcodeVal = localStorage.getItem("myvalue1");
var test2 = localStorage.getItem("code");
code = JSON.parse(test2);
var k = parseInt(localStorage.getItem("counter"));
document.getElementById(code[k]).innerHTML = barcodeVal;
alert(code[k]);
alert(k);
k++;
localStorage["counter"] = k;
localStorage.setItem("code", JSON.stringify(code));
}, function (error) {
alert("Scan failed: " + error);
});

myvalue1是我从扫描中获得的值(value)。我在另一个js文件中定义了一个数组和一个计数器作为

localStorage["counter"]=0;
var code = {};
localStorage.setItem("code", JSON.stringify(code));

现在我试图将 id 存储在数组 code[] 中我正在尝试在 page5.html 中打印它.以上<script>也在同一个 page5.html 中定义.我也一次又一次地调用扫描功能来扫描多个条形码。我将 html 中的值打印为

<tr>
<td>2</td>
<td id="code[0]"></td>
</tr>

我收到错误 Cannot set property 'innerHTML' of null .接下来我该怎么办?请帮我。提前致谢

最佳答案

从JsFiddle here可以看出当你执行指令中的代码[k]时

document.getElementById(code[k]).innerHTML = barcodeVal;

code 不被理解为一个字符串数组,而是一个字符串,所以指向 code[0] 它不是指向你的 id,而是指向括号。

做一个JSON.parse()在更新的 JsFiddle 中的代码上 here

关于javascript - 如何将值存储在数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24449212/

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