Execute JavaScript code stored as a string

前端 未结 20 829
北荒
北荒 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:04

    The eval function will evaluate a string that is passed to it.

    But the use of eval can be dangerous, so use with caution.

    Edit: annakata has a good point -- Not only is eval dangerous, it is slow. This is because the code to be evaluated must be parsed on the spot, so that will take some computing resources.

提交回复
热议问题