无法在 iframe 中使用 JS 填充 src 值
Unable to fill src value using JS in iframe
<!DOCTYPE html>
<html>
<body style="text-align:center;">
<iframe id="gfgFrame" src=""
style="height: 50vh; width: 600px;">
</iframe>
<input type="text" id = "xxx">
<p id = "u"></p>
<button onclick="navigate()">
Click it
</button>
<script>
var url = document.getElementById("xxx");
function navigate() {
document.getElementById("gfgFrame").setAttribute("src", url);
document.getElementById("u").innerHTML = "Hello";
}
</script>
</body>
</html>
如果我输入 URL,它不起作用。
我在 Whosebug 上看到了解决方案。我也试过另一种方法,就是
<script>
var url = document.getElementById("xxx");
function navigate() {
document.getElementById("gfgFrame").src
= url;
}
</script>
请原谅我的故意。谁能告诉我哪里出错了?
您请求的是元素本身,而不是该字段的值,参见:
const urlBlock = document.getElementById("xxx"); // get url text input
function navigate() {
const iframe = document.getElementById("gfgFrame");
const text = document.getElementById("u");
// get url from input
const url = urlBlock.value;
iframe.setAttribute("src", url);
text.innerHTML = "Hello";
}
<iframe id="gfgFrame" src="https://fr.wikipedia.org/wiki/Main_Page" style="height: 50vh; width: 600px;"></iframe>
<input type="text" id="xxx" value="https://wikipedia.org/wiki/Main_Page" />
<p id="u"></p>
<button onclick="navigate()">Click it</button>
<!DOCTYPE html>
<html>
<body style="text-align:center;">
<iframe id="gfgFrame" src=""
style="height: 50vh; width: 600px;">
</iframe>
<input type="text" id = "xxx">
<p id = "u"></p>
<button onclick="navigate()">
Click it
</button>
<script>
var url = document.getElementById("xxx");
function navigate() {
document.getElementById("gfgFrame").setAttribute("src", url);
document.getElementById("u").innerHTML = "Hello";
}
</script>
</body>
</html>
如果我输入 URL,它不起作用。 我在 Whosebug 上看到了解决方案。我也试过另一种方法,就是
<script>
var url = document.getElementById("xxx");
function navigate() {
document.getElementById("gfgFrame").src
= url;
}
</script>
请原谅我的故意。谁能告诉我哪里出错了?
您请求的是元素本身,而不是该字段的值,参见:
const urlBlock = document.getElementById("xxx"); // get url text input
function navigate() {
const iframe = document.getElementById("gfgFrame");
const text = document.getElementById("u");
// get url from input
const url = urlBlock.value;
iframe.setAttribute("src", url);
text.innerHTML = "Hello";
}
<iframe id="gfgFrame" src="https://fr.wikipedia.org/wiki/Main_Page" style="height: 50vh; width: 600px;"></iframe>
<input type="text" id="xxx" value="https://wikipedia.org/wiki/Main_Page" />
<p id="u"></p>
<button onclick="navigate()">Click it</button>