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

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

当前回答

检查了许多复杂和混乱的脚本:

var js = "alert('Hello, World!');" // put your JS code here
var oScript = document.createElement("script");
var oScriptText = document.createTextNode(js);
oScript.appendChild(oScriptText);
document.body.appendChild(oScript);

其他回答

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

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

var F=new Function (theInstructions);

return(F());

如下所示使用eval。Eval应该谨慎使用,一个关于“Eval is evil”的简单搜索应该会抛出一些指针。

function ExecuteJavascriptString()
{
    var s = "alert('hello')";
    eval(s);
}

Eval应该这样做。

eval(s);

同时使用eval和创建一个新函数来执行javascript会带来很多安全风险。

const script = document.createElement("script");
const stringJquery = '$("#button").on("click", function() {console.log("hit")})';
script.text = stringJquery;
document.body.appendChild(script);

我更喜欢这个方法来执行我作为字符串接收的Javascript。

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

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