执行存储为字符串的 JavaScript 代码

2022-08-30 00:55:16

如何执行一些字符串的 JavaScript?

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

答案 1

使用 eval 函数,例如:

eval("my script here");

答案 2

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

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

var F=new Function (theInstructions);

return(F());