javascript - 用document.head.removeChild(script) 移除脚本后,脚本仍能够运行怎么解决?
黄舟
黄舟 2017-04-10 17:35:21
[JavaScript讨论组]

如下面这段脚本:

<body>
<button>click me</button>
<script>

 var btn=document.getElementsByTagName('button')[0];
     var tip=true;
     btn.onclick=function(){
        if (tip===true){
          var sp=document.createElement('script');
              sp.textContent="var time='';"+
                             "var num=1;"+
                             "function test(){console.log(num);num++;setTimeout(test,1000);}"+
                             "test();";
              sp.id='test';
              document.head.appendChild(sp); // 打开控制器可查看脚本已被移除,但是定时器却仍在运行!这简直不可理喻啊!有没有什么办法能够解决?
              tip=false;
        }else if(tip===false){
           tip=null;
           document.head.removeChild(document.getElementById('test'));
        }else{
           return ;
        }
     }

</script>
</body>

我是在使用ajax请求数据的时候遇到的这个问题。

由于需要将 “获取到的内容”去 “替换” 某个 “容器元素” 下的 “原有内容”,然后又由于这些“获取到的内容具有他们自己样式和行为,所以,在更新他们的时候,不能只简单的更新内容就结束了,还需要删除“原先内容”所对应的脚本和样式,然后添加“当前获取到的内容”所对应的样式和脚本。

由此,我才遇到了,移除脚本后,脚本居然还在运行的情况! 求原因和解决办法....

表述比较累赘,请耐心看完,谢谢

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

全部回复(1)
伊谢尔伦
//移除脚本的时候把函数也注销掉。
var btn = document.getElementsByTagName('button')[0];
var tip = true;
btn.onclick = function() {
    if (tip === true) {
        var sp = document.createElement('script');
        sp.textContent = "var time='';" +
            "var num=1;" +
            "function test(){console.log(num);num++;setTimeout(test,1000);}" +
            "test();";
        sp.id = 'test';
        document.head.appendChild(sp); 
        tip = false;
    } else if (tip === false) {
        tip = null;
        document.head.removeChild(document.getElementById('test'));
        test=null;//注销
    } else {
        return;
    }
}
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号