使用eval()来设置全局变量 [英] Using eval() to set global variables

查看:568
本文介绍了使用eval()来设置全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的code。使用评估不工作来设置一个全局变量。这是因为如果分配不叫所有,但没有出现脚本错误。

My code to set a global variable using eval is not working. It's as if the assignment is not called at all, but no script errors occur.

<script type="text/javascript">

    $(function() {

        setTimeout(function() {
            eval('var x = 1;');
            alert(x);
        }, 0);
    });
</script>

<div onclick="alert(x);">Click to see 'x'</div>

在页面加载后,警报显示我的期望;它证实了X = 1,但在那之后,我点击的股利,并得到一个JavaScript错误 X 是不确定的。如何使评估适当加这个变量?

When the page loads, the alert shows what I expect; it confirms that x = 1. But after that, I click on the div and get a javascript error that x is undefined. How do I make eval add this variable properly?

背景:code以上是从一个项目,我的工作,我们必须在AJAX响应执行JavaScript的code一种微创复制的例子。 评估正常工作的大部分时间,但是这导致的问题。

Background: The code above is a minimally reproducing example from a project I'm working on where we must execute javascript code during AJAX responses. eval works properly most of the time, but this is causing problems.

推荐答案

评估和演示在本地运行,你设置一个局部变量。

Eval runs locally, you're setting a local variable.

要设置一个全局变量,删除 VAR ;

To set a global variable, remove var;

<script type="text/javascript">

    $(function() {

        setTimeout(function() {
            eval('x = 1;');
            alert(x);
        }, 0);
    });
</script>

这篇关于使用eval()来设置全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆