JavaScript代码执行不一致

时间:2015-09-21 22:36:14

标签: javascript html

我想读取用户通过拖放提供的图像,并渲染缩略图并将其输出到浏览器。

这是我的代码:

function drop(event)
{
    event.preventDefault();
    var files = event.dataTransfer.files;
    var container = document.getElementById('dragRec');
    var reader = new FileReader();
    reader.onload = function(){
        container.innerHTML += '<img width="250" height="250" src="'+ reader.result +'" />';
    }
    var itCount = files.length;
    for(var i = 0; i < itCount; i++)
    {
        reader.readAsDataURL(files[i]);
    }
}

逐个加载图片时,一切正常。

但是当抓取几个图像时 - 在正常时间执行它将只输出一个图像或(可能)将创建一个没有img的空src标记。

但是,如果我一步一步地运行它(使用FireBug),一切都已加载,一切都很完美(所有图像都存在)。

我想知道是什么原因。

更新

Chris Perkins和kamus让我发现FileReader的异步工作导致在onload处理程序访问它之前清除FileReader.result变量,这意味着img元素将为null src属性。

所以我提出了以下解决方案:

function drop(event)
{
    event.preventDefault();
    var files = event.dataTransfer.files;
    var container = document.getElementById('dragRec');
    var readerList = [];
    var itCount = files.length;
    for(var i = 0; i < itCount; i++)
    {
        readerList.push(new FileReader());
        readerList[i].onload = function(){
            container.innerHTML += '<img width="250" height="250" src="'+ this.result +'" />';
        }
        readerList[i].readAsDataURL(files[i]);
        formData.append('file[]', files[i]);
    }
}

它现在正在运作,但并不像它看起来那样。有什么建议吗?

1 个答案:

答案 0 :(得分:0)

正如您已经注意到main6.py class Barcode(TextInput): l_prompt= ObjectProperty() btext = StringProperty() # capture barcode def onText(self): print ('in onText') c=True while c: print('in loop') time.sleep(1/10) print(self.text) if len(self.text) <=5: c= True else: c = False print('in else') self.l_prompt.change_label('test') Clock.schedule_once(self.parent.run_test,1) class MainLayout(FloatLayout): dt = str(datetime.today()) pafa = '' #pass/fail barcode = '' #barcode number counter = 0 #item counter prompt_wid = ObjectProperty() barcode_wid = ObjectProperty(rebind = True) passfail_wid = ObjectProperty() counterlabel_wid = ObjectProperty() def __init__(self, **kwargs): super(MainLayout, self).__init__(**kwargs) #start test self.starttest(self) self.l=Label() #self.barcode_wid.bind(text=self.l.setter('text')) def detect(self, d): #detect when device is plugged in t = True while t: time.sleep(1) dev = usb.core.find(idVendor= 0x2996) if dev is None: t=False self.prompt_wid.change_label('scan') #label change #self.barcode_wid.focus=True #brings cursor up for input scan j = threading.Thread(target=self.barcode_wid.onText) j.daemon = True j.start() ex6.kv #: kivy 1.9 <MainLayout>: orientation: 'vertical' size: root.size prompt_wid: prompt barcode_wid: barcode passfail_wid: passfail counterlabel_wid: counterlabel canvas.before: Color: rgb: 0, 0, .6 Rectangle: pos: self.pos size: self.size Prompt: id: prompt canvas.before: Color: rgb: .6, .6, .6 Rectangle: pos: self.pos size: self.size Barcode: id: barcode l_prompt: prompt focus: 'True' text:'hey' <Barcode>: pos_hint: {'center_x': .5, 'top': 0.666 } size_hint:(1,.3) font_size: self.height/3 text: '' multiline: 'False' padding: 0,(self.height/3) presentation = Builder.load_file('ex6.kv') class MainApp(App): def build(self): #ml = MainLayout() #Clock.schedule_interval(ml.detect, 2) return MainLayout() if __name__=="__main__": MainApp().run( 行为async的问题。这是另一个选项,如何将FileReader用于多个文件。

&#13;
&#13;
FileReader
&#13;
var bucket = document.getElementById('bucket');

var read = function(file) {
  var reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = function() {
    bucket.innerHTML += "<img src='" + reader.result + "' width='70'/>";
  };
};

var load = function(e) {
  var files = e.dataTransfer.files;
  var l = files.length;
  var img = false;
  var file;
  while (file = files[--l])
    if (file.type.match(/image\/*/)) {
      img = true;
      read(file);
    }
  if (!img)
    bucket.innerHTML = "No image file found ...";
  return false;
};
&#13;
#bucket {
  position: relative;
  height: 60vh;
  margin: 5px;
  border: 2px dashed grey;
  overflow: auto;
  text-align: center;
  padding: 5px;
}
#bucket img {
  border: 1px dotted grey;
  margin: 5px;
}
&#13;
&#13;
&#13;