我正在设置一个网站,我需要的是当单击按钮时它会更改 iframe 中的链接,以便它转到另一个网站。这是我到目前为止所得到的:
<script>
var id = 'http://www.aWebsite.com';
function link(){
id = 'http://www.aSecondWebsite.com'
}
</script>
<script>
document.writeln('<iframe name="heel"src="' + id + '" height="300" width="700"> </iframe>');
</script>
<button onclick="link()">Click Me</button>
我不确定为什么单击按钮时 id 变量没有更改?
最佳答案
实际上id
的值被改变了,但是document.writeln()
不在link
函数中,因此没有被执行。
一个快速修复方法是将 document.writeln()
移至 link()
,但这将是一个灾难性的修复。 document.write(ln)()
在解析页面后使用时,会清除文档中的所有内容并创建一个新文档。你需要做这样的事情:
function link() {
id = 'http://www.example.org';
document.getElementById('heel').src = id;
}
然后将 iframe 元素添加到 HTML,并使用 document.writeln()
删除整个脚本。
<iframe id="heel" name="heel" src="http://www.example.com" height="300" width="700"></iframe>
<小时/>
编辑
如果你想创建一个新的iframe
元素,你可以这样做:
function link() {
var frame = document.createElement('iframe'); // creates an iframe element
id = 'http://www.example.org';
frame.width = '700px'; // sets the width for the new iframe
frame.height = '300px'; // sets the height for the new iframe
frame.name = 'heel2'; // sets the name for the new iframe
frame.src = id; // sets the src for the new iframe
document.body.appendChild(frame); // appends the new iframe to body as a last element
}
关于javascript - 我正在尝试创建一个 iframe,当单击按钮时该 iframe 会发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20145235/