如何在javascript中将变量传递给回调函数(How to pass variable to callback function in javascript)

编程入门 行业动态 更新时间:2024-10-24 03:22:53
如何在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 };

更多推荐

本文发布于:2023-08-06 08:47:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1446688.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中将   回调   变量   函数   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!