javascript传递eval变量 [英] javascript pass eval variables

查看:92
本文介绍了javascript传递eval变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有eval函数,该函数需要从php执行javascript.但是我需要传递元素,因此我可以将鼠标悬停在用户单击的链接上的提示上.

i have eval function, which needs to execute javascript from php. but i need to pass element, so i can put mouse over tips on the link user clicked on.

var globalEval = function globalEval(src, element) {
        if (window.execScript) {
            window.execScript(src);
            return;
        }
        var fn = function(element) {
            window.eval.call(window,src);
        };
        fn(element);
    };

im使用以下方式传递$(this)元素

im using following way to pass $(this) element

globalEval(js_code, $(this));
// js_code is = alert(element);

我收到未定义元素的错误,该错误已在globalEval();中定义,我该如何解决?

i get error of undefined element, which is defined in globalEval(); how can i fix this?

推荐答案

这是一个范围界定问题,因为全局评估未在与变量element相同的作用域内调用代码.如果即使评估是邪恶的,您仍然必须使用eval,则必须以一种可以让您在所需的环境中调用您的代码.一种方法是将其包装为匿名函数,并为所选的环境变量提供参数.

This is a scoping issue as the global eval isn't invoking the code in the same scope as the variable element. If you must use eval even though eval is evil, you'll have to do it in a way that lets you invoke your code in the environment you want. One way to do this is to wrap it as an anonymous function which you give parameters for the environment variables of choice.

例如

window.eval.call(window,'(function (element) {'+src+'})')(element);

这意味着src字符串将被解析,但eval不会调用它,因为它返回一个匿名函数.然后,您调用它并传递您的数据,在本例中为element.

This means the src string is parsed but not invoked by the eval as it returns an anonymous function. You then invoke it, passing your data, in this case element.

使用var element = document.body, src = 'console.log(element.tagName)';测试它,您会看到它记录在"BODY"中.请注意,如果您想以这种方式设置全局变量(或函数),则必须将它们明确声明为全局变量(window.foobar = ...),否则将在匿名函数完成后将它们作为GCd.

Test it with var element = document.body, src = 'console.log(element.tagName)'; and you'll see it log "BODY". Please note that if you want to set global variables (or functions) this way they have to be stated as global explicitly (window.foobar = ...) or they will be GCd after the anonymous function finishes.

这篇关于javascript传递eval变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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