我如何执行一些JavaScript是一个字符串?

function ExecuteJavascriptString()
{
    var s = "alert('hello')";
    // how do I get a browser to alert('hello')?
}

当前回答

您可以使用函数来执行它。例子:

var theInstructions = "alert('Hello World'); var x = 100";

var F=new Function (theInstructions);

return(F());

其他回答

eval(s);

但如果你从用户那里获取数据,这可能是危险的,尽管我想如果他们自己的浏览器崩溃了,那是他们的问题。

您可以使用函数来执行它。例子:

var theInstructions = "alert('Hello World'); var x = 100";

var F=new Function (theInstructions);

return(F());

如果你想在后面执行一个特定的命令(即字符串) 特定的时间 - cmd=你的代码 —InterVal=运行延迟时间

 function ExecStr(cmd, InterVal) {
    try {
        setTimeout(function () {
            var F = new Function(cmd);
            return (F());
        }, InterVal);
    } catch (e) { }
}
//sample
ExecStr("alert(20)",500);

eval函数将对传递给它的字符串求值。

但是eval的使用是超级危险和缓慢的,所以要谨慎使用。

使用eval函数,比如:

eval("my script here");