gpt4 book ai didi

javascript - 如何在javascript中将变量传递给回调函数

转载 作者:行者123 更新时间:2023-11-28 08:34:20 26 4
gpt4 key购买 nike

我有以下代码,但我不太清楚如何将其一直传递到 onload 函数。

我尝试在不同的地方定义它,但没有成功,特别是因为它的定义需要发生在传递给 document.on 方法的函数中,因为我想掌握引用。

$(document).ready(function(e) {
$(document).on('click', "#someId", function(e) {
e.preventDefault();
var variable = $(this).attr('name');

chrome.fileSystem.chooseEntry({
type: 'openFile', accepts:[{
extensions: ['txt']
}]
},
function(fileEntry) {
if (!fileEntry) {
return;
}
fileEntry.file(function(file) {
var reader = new FileReader();
reader.onload = function(e) {
////******* how to access variable here? *******\\\\
chrome.storage.local.set({'txt': e.target.result});
};
reader.readAsArrayBuffer(file);
});
});
});
});

我需要访问 onload 函数内的variable。怎么才能通过呢?

最佳答案

您可以利用closures这样做:

onload = function () {
var variable;
$(document).on('click', "#someId", function(e) {
variable = $(this).attr('name');
// use variable here
});
// and here
};

关于javascript - 如何在javascript中将变量传递给回调函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21431338/

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