lvfujun
V2EX  ›  问与答

js 一个神奇的现象?求解.

  •  
  •   lvfujun · May 6, 2015 · 2752 views
    This topic created in 4208 days ago, the information mentioned may be changed or developed.
    function readerFile(file) {
    var reader = new FileReader();
    window.aaaa = 'aaaa';
    // reader. onload = (function(file) {
    // return function(e) {
    // // window.aaaa = e.target.result;
    // window.aaaa = '1';
    // }
    // })(file);

    reader.addEventListener('load', function(e) {
    window.aaaa = e.target.result;
    }, false);
    reader.readAsDataURL(file);
    alert(window.aaaa)
    }

    以上是我的一个载入文件的函数
    alert(window.aaaa)竟然没有被里面的window.aaaa = e.target.result;给修改掉
    我要怎么在外面获得到
    reader.addEventListener('load', function(e) {
    window.aaaa = e.target.result;
    }, false);
    e.target.result的值啊?????求教为什么把变量挂载到window下也不行啊啊啊啊啊啊啊啊啊啊?????
    7 replies  •  2015-05-06 22:45:49 +08:00
    feiyuanqiu
    feiyuanqiu
    May 6, 2015❤️1
    1
    异步的吧,alert(window.aaaa) 的时候 load 事件还没有触发?
    lemontv
    lemontv
    May 6, 2015❤️1
    2
    文件读取是异步的,用worker来实现同步吧
    morethansean
    morethansean
    May 6, 2015❤️1
    3
    …… 你的 load 是异步事件啊,用 callback 或者 event 的方式告知外部 load 完成吧。执意要挂在 window 下,外部就不停定时循环看有没有结果吧。
    sneezry
    sneezry
    May 6, 2015 via iPhone❤️1
    4
    用回调吧,要不不知道load何时触发呢
    txlty
    txlty
    May 6, 2015❤️1
    5
    修改量最小的办法,延迟几秒。你就发现window.aaaa有值了。 :-D
    setTimeout(function(){alert(window.aaaa)},3000);
    finian
    finian
    May 6, 2015❤️1
    6
    异步异步似爪牙 似魔鬼的步伐
    lvfujun
    lvfujun
    OP
    May 6, 2015
    7
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   3728 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 10:02 · PVG 18:02 · LAX 02:02 · JFK 05:02
    ♥ Do have faith in what you're doing.