怎么用JS实现直接运行html的代码

怎么用JS实现直接运行html的代码

小编给大家分享一下怎么用JS实现直接运行html的代码,希望大家阅读完这篇文章后大所收获,下面让我们一起去探讨吧!

具体如下:

1、实例代码:

<!DOCTYPE html>
<html>
  <head>
    <meta charset='utf-8'/>
    <title>直接运行 html 代码</title>
  </head>
  <body>
    <textarea style='width:300px;height:200px;' id='txtCode'></textarea><br/>
    <input type='button' value='直接运行' id='btnRun'/>
    <script>
      document.getElementById('btnRun').onclick = function(){
        var runHtml = document.getElementById('txtCode').value;
        if(runHtml){
          var win = window.open('', '运行窗口');
          win.document.open();
          win.document.write(runHtml);
          win.document.close();
        }
        else{
          alert('请输入!');
        }
      }
    </script>
  </body>
</html>

2、运行效果图如下:

怎么用JS实现直接运行html的代码

看完了这篇文章,相信你对怎么用JS实现直接运行html的代码有了一定的了解,想了解更多相关知识,欢迎关注行业资讯频道,感谢各位的阅读!