javascript - 我正在尝试创建一个 iframe,当单击按钮时该 iframe 会发生变化

标签 javascript jquery html iframe

我正在设置一个网站,我需要的是当单击按钮时它会更改 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/

相关文章:

javascript - JQuery onChange 获取之前的值

javascript - for..in 循环是否跟踪对象的属性顺序?

javascript - 加载程序在进程完成后才会启动

javascript - 在 Canvas 上的不同绘图上应用阴影

html - IE6,7 在链接悬停上,绝对定位在 child 身上没有改变

javascript - 如何在渐进式披露脚本中切换文本?

javascript - 动态创建的 Html 表对于大量记录渲染速度很慢

jquery - 单击时向输入字段的现有值添加附加值 - jQuery

jquery - 如何使 Bootstrap 日期选择器只读?

jquery - 在 jQuery 中更改 div 的高度