我想做这样的事情:
<body>
<script id="a" >
//Here i do a lot of things, then
document.body.removeChild(document.getElementById("a"));
</script>
</body>
它不工作!
我想做这样的事情:
<body>
<script id="a" >
//Here i do a lot of things, then
document.body.removeChild(document.getElementById("a"));
</script>
</body>
它不工作!
我不确定这是否可行,具体取决于您插入脚本的位置,浏览器甚至可能在完成创建 DOM之前执行代码。在执行代码之前,最好使用像 jQuery 这样的框架并等待文档完成加载。如果你使用 jquery,它会像这样工作:
<script id="a">
$(document).ready(function(){
//do your stuff here
$("#a").remove();
});
</script>
也许试图从自身中删除脚本会导致问题。也许这会奏效......
<script id="a">
var stuffFinished = false;
$(document).ready(function(){
//do your stuff here
stuffFinished = true;
});
</script>
<script id="b">
$(document).ready(function(){
var timer = setInterval(function() {
if (stuffFinished) {
$("#a").remove();
clearTimeout(timer);
}
}, 1000);
});
</script>
我没有测试过这个,只是一个想法......