如何在java脚本中从n级嵌套document.write()打印

时间:2015-06-02 11:12:22

标签: javascript html dom

我有以下代码

<body> 
    <script> 
          (function(s) { })
          ("document.write('<script>document.write(\" <script>document.write('<script>document.write(\"Hello World\");<\/script>');<\/script>\");<\/script>')"); 
    </script> 
</body>

这里在函数体中我应该编写什么代码,以便代码在这里解析并打印Hello World“。这里的解决方案必须适用于document.write()嵌套的n级。 坦率地说,我不知道该怎么做。 有人可以请我提供解决方案

2 个答案:

答案 0 :(得分:0)

抱歉,我会说这没有意义,因为你只是尝试嵌套'document.write()' 'document.write()'的调用将导致整个文档被write参数覆盖。 但是javascript引擎不会再次解析内容。所以即将推出的嵌套代码将无法运行。

除了document.write()可以匹配之外,还有其他目的。但我不知道这样的情况。

如果您尝试在JS中嵌套函数,请尝试

function foo(doBar)
{
  function bar()
  {
    console.log( 'bar' );
  }

  function baz()
  {
    console.log( 'baz' );
  }

  window.baz = baz;
  if ( doBar ) bar();
}

As mentioned here

答案 1 :(得分:0)

 <!doctype html>
    <html> 
        <head>
            <title>Nested document.write()</title> 
        </head>
    <body> 
        <script> 
            //(function(s) { write your code here to parse s and print     "Hello World". Remember - your solution must work for n level of document.write() nesting })( "document.write('<script>document.write(\"<script>document.write('<script>document.write(\"Hello World\");<\/script>');<\/script>\");<\/script>')");

                   (function(s){
                       s = "document.write('<script>document.write(\"<script>document.write('<script>document.write(\"Hello World\");<\/script>\");<\/script>\");<\/script>')";
                       var str, scriptEle = document.createElement('script');
                       str = s.replace(/["']/g, '"');
                       str = str.replace(/"<script>document.write/g, "");
                       str = str.replace(/;<\/script\>"/g, "");
                       scriptEle.innerHTML = str;
                       document.body.appendChild(scriptEle);
                    })();
        </script> 
    </body> 
</html>