使用Javascript将表插入IFRAME

Inserting table into IFRAME using Javascript

本文关键字:插入 IFRAME Javascript 使用      更新时间:2023-09-26

当我单击按钮时,我试图在iframe中插入一个表,但我在方法"pasteHTML"中得到一个错误。下面是我写的代码:

<html>
  <body>
   <input type = "button" onClick="setContent()" value="getContent"></input>
    <iframe id = "iframe" border="0" >
    </iframe>

  <script type="text/javascript">
   var iframe = document.getElementById('iframe');
    iframe.contentDocument.designMode = "on";
    function setContent()
   {
       var iframe = document.getElementById('iframe');
       var str = "<table><tr><td>dushyanth</td></tr></table>";
       var sel = iframe.document.selection.createRange();
       sel.pasteHTML(str);
       sel.select();

   }

  </script>

您是否需要只使用java脚本?。这也可以通过其他方式实现,比如在java脚本函数中使用.load()。

<html>
<head>
  <script type="text/javascript">
    function setContent()   {
      $('divId').load('another.html')
   }
  </script>
</head>
<body>
 <input type = "button" onClick="setContent()" value="getContent"/>
  <div id="divId"></div>
</body>
</html>

another.html

<table>
<tr>
<td>xyz</td>
</tr>
</table>

如果你想使用iframe,那么使用下面的代码,

<html>
<head>
  <script type="text/javascript">
    function setContent()   {
      $('divId').load('iframepage.html')
   }
  </script>
</head>
<body>
 <input type = "button" onClick="setContent()" value="getContent"/>
  <div id="divId"></div>
</body>
</html>

iframepage.html

 <html>
 <body>
<iframe width="500px" height="400" src="anotherpage.html"></iframe>
 </body>    
</html>

anotherpage.html

<table>
<tr>
<td>xyz</td>
</tr>
</table>

试试这个:

var ifr = document.getElementById('iframe');
ifr.src='javascript:"<table><tr><td>dushyanth</td></tr></table>"';

现场演示:http://jsfiddle.net/3Efva/