将DIV添加到iframe正文

时间:2014-01-09 00:33:09

标签: jquery

美好的一天,

我正在尝试将DIV标记添加到iframe正文中。 iframe的内容与我正在处理的网站位于同一个域中,所以这应该不是问题。

<div id="sampleDIV">whatever</div>
<iframe id="custom-frame"></iframe>

在我的javascript代码中,我有:

// load up the the iframe with the data the user selected
$('#custom-frame').attr("src", "/Custom/Data/" + data.id);

// I can get find the body tag in the iframe like:
var iframeBody = $("#custom-frame").contents().find("body");

var styleTag = iframeBody.append($('#sampleDIV'));

*已编辑* 但是当我查看源代码时,我没有看到添加了div标签。当我在Chrome中检查元素时,我没有看到添加了DIV元素。

*已编辑第二部分* 我将标签从DIV更正为IFRAME

我看不出我做错了什么,也许只是盯着这个太久了。

TIA,

COSON

1 个答案:

答案 0 :(得分:5)

你能用iframe发布完整的HTML吗?在上面的示例中,您有两个div,代码正在尝试添加到第二个div,而不是iframe。

这对我有用:

<div id="sampleDIV">whatever</div>
<iframe id="custom-frame" src="page2.html" width="500" height="500"></iframe>


<script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>   

<script>
    $(function() {
        var iframeBody = $("#custom-frame").contents().find("body");
        var styleTag = iframeBody.append($('#sampleDIV'));
    })
</script>
相关问题