在执行onload时如何更改变量

时间:2018-12-26 07:51:33

标签: javascript scope

我正在尝试将图像加载到画布中。我想在执行onload函数时获取变量。

dict = {"k1":1, "k2":2, "k3":3}
current=""
current_k=""
for k,v in dict.items():
    for i in k:
        current_k=i+current_k
    current=str(v)+current_k+current
print(current)
print(current_k)

我也尝试了以下方法。但这对我不起作用。 以下方法返回的值为function getResponse(srcImg){ var img = new Image(); var loaded = false; img.src = srcImg; img.onload = function(){ loaded = true; } // i want to get loaded variable when the onload function is complete // wait the return value until the img is not loaded return loaded; } getResponse(imageURL); //loaded is false

undefined

2 个答案:

答案 0 :(得分:1)

这是异步行为。您可以使用回调或Promise。看下面:

function getResponse(srcImg,callback){

    var img = new Image();
    var loaded = false;
    img.src = srcImg;

    img.onload = function(){
      loaded = true;
      callback(loaded)
      }
     // i want to get loaded variable when the onload function is complete
     // wait the return value until the img is not loaded
     return loaded;
}

getResponse(imageURL,(load)=>{});

答案 1 :(得分:0)

像这样使用回调

model_size
def rate(self, step = None):
    "Implement `lrate` above"
    if step is None:
        step = self._step
    return self.factor * \
        (self.model_size ** (-0.5) *
        min(step ** (-0.5), step * self.warmup ** (-1.5)))