我从 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 中的值,使其成为正确的语法。
最佳答案
我认为代码运行得太早,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>
关于javascript - 动态更改 Iframe src,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52095654/