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

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

当前回答

Stefan的回答延伸如下:

//Executes immediately function stringToFunctionAndExecute(str) { let func = new Function(str); return (func()); // <--- note the parenteces } //Executes when called function stringToFunctionOnly(str) { let func = new Function(str); return func; } // -^-^-^- Functions -^-^-^- (feel free to copy) // -v-v-v- Explanations -v-v-v- (run code to read easier) console.log('STEP 1, this executes directly when run:') let func_A = stringToFunctionAndExecute("console.log('>>> executes immediately <<<')"); console.log("STEP 2, and you can't save it in a variable, calling a() will throw an error, watch:") try { func_A(); } catch (error) { console.log('STEP ERROR, see, it failed', error) } console.log('STEP 3, but this will NOT execute directly AND you can save it for later...') let func_B = stringToFunctionOnly("console.log('>>> executes when called <<<')"); console.log("STEP 4, ...as you see, it only run when it's called for, as is done now:") func_B(); console.log('STEP 5, TADAAAAA!!')

其他回答

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

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

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

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 script = "<script type='text/javascript'> content </script>";
  //using jquery next
  $('body').append(script);//incorporates and executes inmediatelly

就我个人而言,我没有测试它,但似乎可以工作。

Stefan的回答延伸如下:

//Executes immediately function stringToFunctionAndExecute(str) { let func = new Function(str); return (func()); // <--- note the parenteces } //Executes when called function stringToFunctionOnly(str) { let func = new Function(str); return func; } // -^-^-^- Functions -^-^-^- (feel free to copy) // -v-v-v- Explanations -v-v-v- (run code to read easier) console.log('STEP 1, this executes directly when run:') let func_A = stringToFunctionAndExecute("console.log('>>> executes immediately <<<')"); console.log("STEP 2, and you can't save it in a variable, calling a() will throw an error, watch:") try { func_A(); } catch (error) { console.log('STEP ERROR, see, it failed', error) } console.log('STEP 3, but this will NOT execute directly AND you can save it for later...') let func_B = stringToFunctionOnly("console.log('>>> executes when called <<<')"); console.log("STEP 4, ...as you see, it only run when it's called for, as is done now:") func_B(); console.log('STEP 5, TADAAAAA!!')

使用eval()。

W3学校评估之旅。网站有一些有用的例子的评估。Mozilla文档详细介绍了这一点。

你可能会得到很多关于安全使用的警告。不允许用户向eval()中注入任何东西,因为这是一个巨大的安全问题。

您还需要知道eval()具有不同的作用域。