简体   繁体   English

Return 语句未按预期工作

[英]Return statement doesn't work as intended

So I was working with this line of code to convert an input image into an URL, however, the return doesn't seem to be working as I can't access the constant anywhere else in the document where I actually need it.因此,我正在使用这行代码将输入图像转换为 URL,但是,返回似乎不起作用,因为我无法在文档中实际需要它的其他任何地方访问该常量。

window.addEventListener('load', function() {
            document.querySelector('input[type="file"]').addEventListener('change', function() {
                if (this.files && this.files[0]) {
                    const imageURL = URL.createObjectURL(this.files[0]);
                    return imageURL;
                }
            });
          });       

I'm still new to JavaScript so for the life of me I can't find why it doesn't work, thanks in advance!我对 JavaScript 还是很陌生,所以在我的一生中,我找不到它为什么不起作用,在此先感谢!

That's because constant imageURL is scoped in if block, if you want it to be accessed in whole file declare it outside addEventListener() function.这是因为常量 imageURL 的范围在 if 块中,如果您希望在整个文件中访问它,请在 addEventListener() 函数之外声明它。 For eg例如

let imageURL;
window.addEventListener('load', function() {
            document.querySelector('input[type="file"]').addEventListener('change', function() {
                if (this.files && this.files[0]) {
                    imageURL = URL.createObjectURL(this.files[0]);
                    
                }
            });
          });

console.log(imageURL)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM