leehon
V2EX  ›  问与答

前端问题:页面刷新后,脚本运行不正常了

  •  
  •   leehon · Apr 29, 2016 · 2626 views
    This topic created in 3688 days ago, the information mentioned may be changed or developed.
    需求是不断刷新页面,获取页面中的一个值。我借鉴了一段在 chrome 控制台运行的代码,能正常工作

    var timeout = 1000;
    current = location.href;
    setTimeout('reload()', timeout);
    function reload() {
    setTimeout('reload()', timeout);
    fr4me = '<frameset cols=\'*\'>\n<frame src=\'' + current + '\'/>';
    fr4me += '</frameset>';
    with(document) {
    write(fr4me);
    void(close())
    };
    }
    获取页面数据的需求,我写了如下代码:

    var content = document.getElementsByTagName('html')[0].innerHTML;
    var id = content.substring(content.indexOf('id:'),content.indexOf(','));
    cosole.info(id);

    我试过把代码添加到 reload()函数,第一次是正常的。页面刷新以后,就获取不到值了,求解应该放在哪里,能在每次刷新页面后都正常
    3 replies    2016-04-29 23:47:36 +08:00
    ss098
        1
    ss098  
       Apr 29, 2016   ❤️ 1
    没有细看代码,需求看的也不是太懂,根据文字描述臆测出以下内容:

    刷新页面后页面将重新加载,故页面中的所有 JavaScript 变量将重新初始化。可能正确的解决方案是使用 HTML5 本地化存储 API ,例如 localStorage 。
    horizon
        2
    horizon  
       Apr 29, 2016 via iPhone   ❤️ 1
    不忍直视的代码
    leehon
        3
    leehon  
    OP
       Apr 29, 2016
    @ss098
    @horizon
    谢谢,发现问题了。刷新以后,获取到的内容是框架那几句代码,最终写了个简单的 php
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3137 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 42ms · UTC 14:31 · PVG 22:31 · LAX 07:31 · JFK 10:31
    ♥ Do have faith in what you're doing.