替换iframe src

时间:2018-06-11 02:12:13

标签: javascript html iframe

如果我为此创建了新线程,请道歉,但我没有在其他地方获得解决方案。 我是网页设计的新手,我正在玩<iframe>标签。

我使用javascript显示Google Sheets的图形图表。每次我点击打开图表的链接(由iframe连接)时,图表会再次显示在上一个图表下方,我的HTML页面会变长。我不希望这种情况发生。相反,我想用以前生成的图表的相同边距中的新图表替换旧图表。

<script>
function myFunction() {
    var x = document.createElement("IFRAME");
    x.setAttribute("src", "#Link_to_Google_sheet_chart");
    x.height = "400";
    x.width = "545";
    x.style.margin = "100px 20px 200px 450px";
    document.body.appendChild(x);
}
</script>

2 个答案:

答案 0 :(得分:0)

首先,您不应该使用前缀为#的链接。使用https://link.com

你试过这个吗?

x.src = "https://link.com";

如果这不起作用,可以试试这个:

function myFunction() {
    var x = document.createElement("IFRAME");
    x.setAttribute("src", "https://link.com");
    x.height = "400";
    x.width = "545";
    x.style.margin = "100px 20px 200px 450px";
    x.id = "iframe-0";
    document.body.appendChild(x);
}
function switch() {
    document.getElementById('iframe-0').style.display = "none";
    // create new iframe here, then append it
    var y = document.createElement("IFRAME");
    y.setAttribute("src", "https://link.com");
    y.height = "400";
    y.width = "545";
    y.style.margin = "100px 20px 200px 450px";
    y.id = "iframe-1";
    document.body.appendChild(y);
}

答案 1 :(得分:0)

您可以为iframe分配ID,然后下次将其替换为

function myFunction() {
    var x = document.getElementById('unique-id');
    if(typeof(x) !== 'undefined'){ //if iframe is appended only change src
      return x.setAttribute("src", "#Link_to_Google_sheet_chart");
    }
    x = document.createElement("IFRAME");
    x.id = 'unique-id';
    x.setAttribute("src", "#Link_to_Google_sheet_chart");
    x.height = "400";
    x.width = "545";
    x.style.margin = "100px 20px 200px 450px"; 
    return document.body.appendChild(x);

}
相关问题