2013-03-01 118 views
0

我試圖在iframe中插入表格時單擊按鈕,但在「pasteHTML」方法中出現錯誤。 這裏是我寫的代碼:使用Javascript插入表格到IFRAME中

<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> 

回答

1

有必要讓你只使用Java腳本? 。這可以通過其他方式實現,例如在java腳本函數中使用.load()。

+0

是的,我對Java腳本只工作 – Dushyanth 2013-03-01 12:05:46

+0

我會後的代碼示例看到,你 – 2013-03-01 12:10:18

0
<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> 
+0

我在這裏利用jQuery的原理函數.load() – 2013-03-01 12:25:51

+0

是否在iframe的特定位置插入表? – Dushyanth 2013-03-01 12:26:40

+0

這裏我沒有使用iframe,我只是插入另一個HTML頁面,包含您的表格到您當前的HTML頁面的div標籤。如果你想使用Iframe,那麼你在上面的代碼中做一些修改。 – 2013-03-01 12:40:10

0

如果你想使用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> 
0

試試這個:

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

現場演示:http://jsfiddle.net/3Efva/