在javascript中用iframe替换div

时间:2012-02-24 16:39:53

标签: javascript dom html

我在页面上有一个div,例如:

<div>
   <p>This is a div, but it should be an iframe.</p>
   <p>Here, all kind of stuff could be inside.</p>
   <table>
     <tr>
       <td>something</td>
     </tr>
   </table>
</div>

我想用iframe替换div,得到类似的东西:

<iframe>
   <html><body>
   <p>This is a div, but it should be an iframe.</p>
   <p>Here, all kind of stuff could be inside.</p>
   <table>
     <tr>
       <td>something</td>
     </tr>
   </table>
   </body></html>
</iframe>

怎么做?一个纯粹的javascript解决方案是最好的,但是使用JJery的ExtJs的解决方案也可以。

3 个答案:

答案 0 :(得分:2)

试试这个:

<!DOCTYPE html>
<html>
    <head>
        <script>
            var p = {
                onload: function() {
                    var div = document.getElementById("div");
                    var iframe = document.createElement("iframe");
                    document.body.appendChild(iframe);
                    iframe.innerHTML = div.innerHTML;
                    div.parentNode.removeChild(div);
                }
            };
        </script>
    </head>
    <body onload="p.onload()">
        <div id="div">
            <p>This is a div, but it should be an iframe.</p>
            <p>Here, all kind of stuff could be inside.</p>
            <table>
                <tr>
                    <td>something</td>
                </tr>
            </table>
        </div>
    </body>
</html> 

答案 1 :(得分:1)

既然你说jQuery解决方案是可以接受的,那么:

首先,我们假设您的div的ID为remove-my-contents

接下来,我们可以做到

$('#remove-my-contents').html('your iframe code goes here');

它不会移除<div>,但会使用您的<iframe>代码替换其内容。

希望这有帮助。

答案 2 :(得分:-1)

啊,似乎Firefox的问题是iframe一直保持空白。看到: Replace div with iframe in javascript