简体   繁体   English

在JavaScript中,如何将值从未命名函数传递给另一个未命名函数?

[英]In JavaScript, how can I pass value from unnamed function to another unnamed function?

I have two functions, one of which checks if an image loads: 我有两个功能,其中一个检查图像是否加载:

var img = document.createElement('img');
img.src = "xxx";
img.onload = function() {
    var dimensionValue = 'loaded';
};
img.onerror = function() {
    var dimensionValue = 'failed';
}

A subsequent function executes when a user clicks a button, like so: 当用户单击按钮时,将执行后续函数,如下所示:

var trackClick = function(url) {
  console.log(dimensionValue);
};

I am trying to log the value of dimensionValue at the point the trackClick function is called (from an a link). 我想记录的值dimensionValue在点trackClick函数被调用(从a链接)。 However, despite the first function succesfully printing out the dimensionValue, when the second function is triggered it contains no value or it fails to indicate that dimensionValue does not exist. 但是,尽管第一个函数成功打印出了DimensionValue,但是当触发第二个函数时,它不包含任何值,或者无法指示该dimensionValue不存在。

I have also attempted to place the trackClick within the onload / onerror functions, but then a message displays informing that there is no function called trackClick 我还尝试将trackClick放在onload / onerror函数中,但是随后显示一条消息,通知您没有名为trackClick函数

So, my question is how to pass a value from one unnamed function to another anonymous function in JS? 因此,我的问题是如何在JS中将一个未命名函数的值传递给另一个匿名函数?

Your variable might not be able to be accessed by the other function because it is defined in another function. 您的变量可能无法被其他函数访问,因为它是在另一个函数中定义的。

Try: 尝试:

var dimensionValue;
var img = document.createElement('img');
img.src = "xxx";
img.onload = function() {
    dimensionValue = 'loaded';
};
img.onerror = function() {
    dimensionValue = 'failed';
}

I think you could also do: 我认为您也可以:

var trackClick = function(url) {
    var img = document.createElement('img');
    img.src = "xxx";
    img.onload = function() {
        console.log('loaded');
    };
    img.onerror = function() {
        console.log('failed');
    }
}

If this doesn't work, please post all of your code for further assistance. 如果这不起作用,请发布所有代码以获取进一步的帮助。

By declaring dimensionValue outside of your functions, you widen the scope that can access it. 通过在函数外部声明dimensionValue ,可以扩展可以访问它的范围。 Assuming your trackClick function is in the same scope, it should have access to dimensionValue . 假设您的trackClick函数在同一作用域内,那么它应该可以访问dimensionValue

var dimensionValue
var img = document.createElement('img');
img.src = "xxx";
img.onload = function() {
    dimensionValue = 'loaded';
};
img.onerror = function() {
    dimensionValue = 'failed';
}

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

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