问题描述
我在写剧本的GreaseMonkey(使用JQuery),我需要的是通过一个脚本在原来的页面中设置一些变量,像这样的:
<脚本类型=文/ JavaScript的>
变种RDATA = {20982211:[1,0,1],20981187:[8,0,4]};
< / SCRIPT>
我取的另一页元素,并尝试对eval它,把奇怪的是这不工作:
$。获得(link_url,空,功能(数据){
警报(1+ RDATA);
的eval($(数据).find(脚本)文本());
警报(2+ RDATA);
}
但奇怪的是Firebug控制台它工作(我只是尝试了EVAL直接在targetpage没有。获得),当我运行的脚本,但事实并非如此。它使我在这两个警报空。
任何想法?
的ECMAScript 5重新定义评估
,以便它不能添加变量绑定到封闭的词法环境。
<一个href="http://whereswalden.com/2011/01/10/new-es5-strict-mode-support-new-vars-created-by-strict-mode-eval-$c$c-are-local-to-that-$c$c-only/" rel="nofollow">http://whereswalden.com/2011/01/10/new-es5-strict-mode-support-new-vars-created-by-strict-mode-eval-$c$c-are-local-to-that-$c$c-only/有关问题的评估
会谈ES 3下。
VAR伏;
功能测试(code)
{
的eval(code);
返回伏;
}
一种可能的解决问题的方法是使用不同的评价构建体,如(新功能(警报(RDATA);+ ... +;警报(RDATA);'))
引入了一个完整的词法环境
i'm writing a GreaseMonkey script (using JQuery), and i need some variables that are set by a script in the original page, like this:
<script type="text/javascript">
var rData = {"20982211":[1,0,1],"20981187":[8,0,4]};
</script>
I fetch this element from another page and try to eval it, put strangely this doesn't work:
$.get(link_url, null, function(data) {
alert("1:" + rData);
eval($(data).find("script").text());
alert("2:" + rData);
}
The strange thing is on the firebug console it works (i just tried the eval directly on the targetpage without the .get), when i run the script though it doesn't. It gives me "null" in both alerts.
Any ideas?
EcmaScript 5 redefined eval
so that it cannot add variable bindings to the enclosing lexical environment.
http://whereswalden.com/2011/01/10/new-es5-strict-mode-support-new-vars-created-by-strict-mode-eval-code-are-local-to-that-code-only/ talks about the problems with eval
under ES 3.
var v;
function test(code)
{
eval(code);
return v;
}
One possible solution to your problem is to use a different evaluation construct, e.g. (new Function('alert(rData); ' + ... + '; alert(rData);'))
introduces a complete lexical environment.
这篇关于里面的eval(JavaScript的)设置变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!