FileReader.onload 怎么传递额外的参数给onload函数

这是官方文档的用法:

// Callback from a <input type="file" onchange="onChange(event)">
function onChange(event) {
  var file = event.target.files[0];
  var reader = new FileReader();
  reader.onload = function(event) {
    // The file's text will be printed here
    console.log(event.target.result)
  };

  reader.readAsText(file);
}

但如果我想传递一个参数给function(event){}, 应该怎么做,我试过如下定义:

var a = 1;
reader.onload = function(event, a) {
    // The file's text will be printed here
    console.log(event.target.result)
  };
阅读 9.1k
2 个回答

传递参数给function是你主动执行了funtion才能传递,类似onload 的触发机制其实是被动的,里面的参数也就固定了,想要在onload 里面使用其它参数就自己在外部定义,然后里面使用

var a = 1;
reader.onload = function(event) {
    console.log(a); // 这里直接使用
    console.log(event.target.result)
};
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题