如何在jquery中选择div并将其替换为iframe

时间:2013-12-23 10:57:27

标签: javascript jquery html iframe

我有jquery代码,已设置为选择名为wrap的'div'。

我想要做的是将选中的“div”更改为标识为news的“iframe”。

我尝试过一些事情并没有设法让它发挥作用。以下是我的代码

$('document').ready(function () {
    var $wrap = $('#wrap'),
        page = 1;

    $('#next').on('click', function () {
        getPage(++page);
    });

    $('#prev').on('click', function () {
        getPage(--page);
    });

    var getPage = function (page) {
        $wrap.load('proxy.php?page=' + page + ' #postsArea');
    };

    getPage(page);

});

以下是生成的HTML

<body>
<div id="wrap">
</div>
<button type="button" id="next">Next</button>
<button type="button" id="prev">Previous</button>
</body>

以下是我要将其更改为

的内容
<body>
<iframe id="news">
</iframe>
<button type="button" id="next">Next</button>
<button type="button" id="prev">Previous</button>
</body>

6 个答案:

答案 0 :(得分:3)

“我想要做的是将所选的'div'更改为带有id新闻的'iframe'。”

这是如何做到的,并在你编写的函数中为它提供你想要的URL。

var getPage = function (page) {
    $("#news").replaceWith($('<iframe>', {
        src:'proxy.php?page=' + page + ' #postsArea',
        id:'news'
    }));
};

http://jsfiddle.net/2qSAD/

虽然有人提到,但最好先使用iframe。如果你想隐藏它直到你需要它(这可能是你使用div的原因)你可以这样做。

<iframe id="news" style="display:none;"></iframe>

JQ

var getPage = function (page) {
    $("#news").prop('src', 'proxy.php?page=' + page + ' #postsArea').show();
};

答案 1 :(得分:1)

试试这个:

document.getElementById('news').src = "proxy.php?page="+page+"#postsArea";

答案 2 :(得分:1)

使用src属性更改iframe来源

$('#news').attr('src', "proxy.php?page="+page+"#postsArea")

答案 3 :(得分:1)

如果你想替换一个完整的元素,我建议瞄准它的父母:

$("#mydiv").parent().html("<iframe>....</iframe>");

html()返回元素的INNER html。所以父母的内心就是元素本身。

答案 4 :(得分:1)

你能不能使用JQ查询replaceWith ..

  $( "div#wrap" ).replaceWith('<iframe id="news" src=".."></iframe);

答案 5 :(得分:1)

尝试使用outerHTML:

document.getElementById("wrap").outerHTML="<iframe id='news'></iframe>";

以下是小提琴:

http://jsfiddle.net/uZsmq/