首页 > 解决方案 > 动态更改 iframe src

问题描述

我从 localstorage 获得价值,并希望将其传递给 iframe 中的 url。我正在尝试这段代码

<script>
  // getting value from localstorage

  var x = localStorage.getItem("firstname");
  //alert showing the value 

  alert(x);
  //but this is not working.
  document.getElementById("framee").src = 'https://thingspeak.com/channels/' + x + '/charts/1?bgcolor=%23ffffff&color=%23d62020&dynamic=true&results=60&type=line&update=15';
</script>

<body>

  <iframe id="framee"></iframe>

</body>

警报向我显示了值,但是当执行下一行时,网络上没有显示任何框架。问题是如何在 url 中传递值,以便它可以是正确的语法。

标签: javascriptjquery

解决方案


我认为代码运行得很早,JS 尝试找到具有该 id 的元素,但没有元素,因为未加载正文。尝试将代码放置到页面底部或将其放入函数中并在例如页面加载时执行该函数。

    <script>
    function loadIframe(){
    // getting value from localstorage

    var x = localStorage.getItem("firstname");
    //alert showing the value 

    alert(x);
    //but this is not working.
    document.getElementById("framee").src='https://thingspeak.com/channels/' + x +'/charts/1?bgcolor=%23ffffff&color=%23d62020&dynamic=true&results=60&type=line&update=15';
    }
    </script>

    <body onLoad="loadIframe()"> 

    <iframe id="framee" ></iframe>

    </body>

推荐阅读