如何在javascript中将变量传递给回调函数(How to pass variable to callback function in javascript)
我有以下代码,我不太清楚如何将它一直传递给onload函数。
我试图在不同的地方定义它但没有成功,特别是因为它的定义需要在传递给document.on方法的函数中发生,因为我想得到this引用的保留。
$(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 。 我怎么通过呢?
I have the following piece of code, and I'm not very clear on how to pass it all the way down to the onload function.
I have tried to define it in different places but without success, especially because its definition needs to happen in the function passed to the document.on method, since I want to get the hold of the this reference.
$(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); }); }); }); });I need to access variable inside the onload function. How can I pass it?
最满意答案
您可以利用闭包执行此操作:
onload = function () { var variable; $(document).on('click', "#someId", function(e) { variable = $(this).attr('name'); // use variable here }); // and here };You could take advantage of closures doing this :
onload = function () { var variable; $(document).on('click', "#someId", function(e) { variable = $(this).attr('name'); // use variable here }); // and here };更多推荐
发布评论