admin管理员组文章数量:1356288
Hope this jquery based simple code will help to explain the issue.
html:
<script>
$('#remover').click(function(){
$('#block').empty();
})
$('#test').click(function(){
alert(remove1); // still displays the varibale
})
</script>
<div id="block">
<script>
var remove1 = 'asasdsds';
var remove2 = 'asasdsds';
var remove3 = 'assdsdsdas';
var blabla = 'blablabl';
</script>
</div>
<span id="remover">Remove ALL</span>
<span id="test">Test</span> // it will still displays the variable.
I need to clear all variables from global scope by removing the block content. The block content is dynamic and can contain any javascript code.
Thanks for reading.
Hope this jquery based simple code will help to explain the issue.
html:
<script>
$('#remover').click(function(){
$('#block').empty();
})
$('#test').click(function(){
alert(remove1); // still displays the varibale
})
</script>
<div id="block">
<script>
var remove1 = 'asasdsds';
var remove2 = 'asasdsds';
var remove3 = 'assdsdsdas';
var blabla = 'blablabl';
</script>
</div>
<span id="remover">Remove ALL</span>
<span id="test">Test</span> // it will still displays the variable.
I need to clear all variables from global scope by removing the block content. The block content is dynamic and can contain any javascript code.
Thanks for reading.
Share Improve this question asked Apr 24, 2009 at 16:27 tarastaras 2,2836 gold badges36 silver badges43 bronze badges2 Answers
Reset to default 7This certainly won't work as you expect. The JavaScript heap is not coupled to the DOM - once scripts have executed, and mutated the heap, you can't "unexecute" them by removing their associated source code.
Global variables are typically set on the window object, so if you know the names, you can remove them from there. If you want to undo the effects of any JavaScript inside the block, you're pretty much out of luck.
Javascript doesn't work that way! Once a script block is parsed, removing it from the DOM won't do anything... The only thing I can think of is a really ugly hack like this:
<script>
var blockKeys = [];
var oldKeys = {};
for (var i in window)
oldKeys[i] = true;
</script>
<div id="block">
<script>
var remove1 = 'asasdsds';
var remove2 = 'asasdsds';
var remove3 = 'assdsdsdas';
var blabla = 'blablabl';
</script>
</div>
<script>
for (var i in window)
{
if (!oldKeys[i])
blockKeys.push(i);
}
alert(remove1);
</script>
Then your remove function looks like:
<script>
function remove()
{
for(var i = 0; i < blockKeys.length; i++)
eval(blockKeys[i] + ' = null');
}
</script>
本文标签: jqueryCleaning javascript variable scope by removing it39s code from DOMStack Overflow
版权声明:本文标题:jquery - Cleaning javascript variable scope by removing it's code from DOM - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744048788a2582033.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论