全局变量无法在js中重置

时间:2015-11-23 03:38:20

标签: javascript jquery

这是一个简单的脚本:

    var _URL = window.URL || window.webkitURL;
    var img; 
    var img_width = 0; 
    var img_height = 0;
    var f = $(this)[0].files[0];  
    if (f != null) {
      if (f.type == 'image/jpeg') {
        img = new Image();
        img.onload = function () {
          img_width = this.width;  //why not $(this)??
          img_height = this.height;
          alert(img_width + ' x ' + img_height);  //1st alert
        };
        img.src = _URL.createObjectURL(f);
        alert(img_width + ' x ' + img_height); //2nd alert
      };
    };

img_width& img_height是全局变量,其值将使用img.onload重置。执行脚本时,first alert显示宽度和高度。但是,2nd alert始终显示0 x 0。为什么在img_width内没有重置gloabl var img_heightimg.onload以便在主线程中使用?

0 个答案:

没有答案
相关问题