【问题标题】:Load frame, only after clicking over "Load" button加载框架,仅在单击“加载”按钮后
【发布时间】:2017-10-05 13:33:09
【问题描述】:

我希望 iframe 仅在按下加载按钮时加载。

<html>
    <body>
        <iframe src="page.html" id="push_frame">
Frames are not supported.
        </iframe>
        <button id="load_frame">
            Load
        </button>
    </body>
</html>

通常这需要某种 JavaScript 来解决。我该如何实现?

【问题讨论】:

  • 请出示所需的javascript或其他代码
  • 以空的src 开头,然后在您的按钮点击事件中指定。
  • @Walk 完美的想法。添加必要的代码(如
  • 无法帮助您,抱歉。

标签: javascript html iframe


【解决方案1】:

我就是这样做的,将你的 url 存储在 data 属性中,然后在你的点击事件中检索它。

function loadFrame() {
  var frame = document.getElementById('push_frame');
  frame.src = frame.dataset.src;
}
<html>

<body>
  <iframe data-src="page.html" src="" id="push_frame">
Frames are not supported.
</iframe>
  <button id="load_frame" onclick="loadFrame()">
Load
</button>
</body>

</html>

【讨论】:

  • 够了!我有 3 个分析器
【解决方案2】:

我会使用 jQuery 来指定新的attr。它看起来更干净,并且减少了代码行数。

$('#load_frame').on('click', function() {
    $('#push_frame').attr('src', 'page.html');
});

我已经提出了一个工作小提琴here

【讨论】:

  • jQuery 库中的所有代码行除外 ;)
【解决方案3】:

使用这个

document.getElementById('load_frame').onclick = function() {

   var iframe = document.createElement('iframe');
   iframe.src = 'page.html';
   document.body.appendChild(iframe);

};

【讨论】:

  • 我没有测试过这段代码,但是改变src属性的想法很完美。所以,我会接受这个答案。
猜你喜欢
相关资源
最近更新 更多
热门标签