Execute JavaScript code stored as a string

前端 未结 20 1031
北荒
北荒 2020-11-22 08:58

How do I execute some JavaScript that is a string?

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


        
20条回答
  •  悲&欢浪女
    2020-11-22 09:24

    Using both eval and creating a new Function to execute javascript comes with a lot of security risks.

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

    I prefer this method to execute the Javascript I receive as a string.

提交回复
热议问题