我使用 hrome.storage.local.get 编写了一个简单的函数
chrome.storage.local.get(['valueInput'], (result) => {
if (typeof result.valueInput !== 'undefined') {
let selectorInput = document.querySelectorAll('input');
result.valueInput.forEach((item, index) => selectorInput[index].value = item);
}
});
我将此代码拼接到独立函数
function getFromeStorage(value) {
let arr = [];
chrome.storage.local.get(value, (result) => {
if (typeof result.valueInput !== 'undefined') {
result.valueInput.forEach((item, i) => arr[i] = item);
}
});
return arr;
\\ Array(18)[0: "3" 1: "1" 2: "1" 3: "1" 4: "1" 5: "1" 6: "1" 7: "1" 8: "1" 9: "1" 10: "1" 11: "1" 12: "1" 13: "1" 14: "1" 15: "1" 16: "1" 17: "1"]
}
但是当我拼接这个函数时,这个函数就不起作用了
let selectorInput = document.querySelectorAll('input');
let valueInput = getFromeStorage("valueInput");
valueInput.forEach((item, index) => selectorInput[index].value = item);
HTML
<tr>
<td class="center-align">Administrowanie systemami operacyjnymi</td>
<td class="center-align row">
<input type="number" class="input-default-weight" min="1" max="20" value="1">
<i id="hint-default-weight" class="material-icons md-dark center-vertically tooltipped hint" data-position="top" data-delay="250" data-tooltip="Ilość lekcji w tygodniu" data-tooltip-id="1b1400b4-3270-0b0c-da17-8540ce6f2408">info_outline</i></td>
<td class="center-align">5</td>
<td class="center-align yearPresent">86%</td>
</tr>
这是相同的代码,但我只将我的主代码拼接到函数中,并在我的代码中调用它。我该如何解决这个问题?
最佳答案
您似乎正在返回 arr
调用回调之前变量,因此它始终返回一个空数组。
function getFromeStorage(value) {
let arr = [];
chrome.storage.local.get(value, (result) => {
// This function won't fill 'arr' until later
if (typeof result.valueInput !== 'undefined') {
result.valueInput.forEach((item, i) => arr[i] = item);
}
});
// This empty 'arr' gets returned too early
return arr;
自 chrome.storage.local.get
是异步的,您访问它的函数必须处理它。一种方法是向函数添加回调或 Promise。为了简单起见,下面是回调的样子:
function getFromeStorage(value, callback) {
chrome.storage.local.get(value, (result) => {
const arr = [];
if (typeof result.valueInput !== 'undefined') {
result.valueInput.forEach((item, i) => arr[i] = item);
}
callback(arr);
});
}
然后,您必须更改使用该函数的方式来等待 callback
像这样调用:
let selectorInput = document.querySelectorAll('input');
let valueInput = getFromeStorage("valueInput", (valueInput) =>{
valueInput.forEach((item, index) => selectorInput[index].value = item);
});
关于javascript - 更改数组中所有输入的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61098595/