我正在尝试创建一个iframe,它在单击按钮时会发生更改

I am trying to create an iframe that changes when a button is clicked

本文关键字:按钮 单击 一个 创建 iframe      更新时间:2023-09-26

我正在建立一个网站,我需要的是当点击一个按钮时,它会更改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   
}