如何在菜单项的点击中重新加载iframe的内容

时间:2018-11-09 17:07:10

标签: javascript html

我想通过单击菜单项来更改iframe的内容。但是由于某些原因,iframe的内容无法刷新。

HTML

<div class="switcher">
  <a href ="https://codepen.io/shawkdsn/pen/rLIgC">Option 1</a>
  <a href ="https://codepen.io/shawkdsn/pen/ejBJw">Option 2</a>
</div>

<iframe class="switch-target" width="300" height="300" src=""></iframe>

JavaScript

var switcher$ = $('.switcher');
var switchTarget$ = $('.switch-target');

switcher$.on('click', switchIframeSrc);

function switchIframeSrc() {
  switchTarget$.attr('src', switcher$.val());
}

// call the method on load
switchIframeSrc();

2 个答案:

答案 0 :(得分:2)

有点晚了,但是您不需要任何JavaScript。只需为您的<iframe>元素提供一个name属性,并将该名称用作超链接的target

<div class="switcher">
  <a href ="https://codepen.io/shawkdsn/pen/rLIgC" target="switch-frame">Option 1</a>
  <a href ="https://codepen.io/shawkdsn/pen/ejBJw" target="switch-frame">Option 2</a>
</div>

<iframe class="switch-target" width="300" height="300" src="" name="switch-frame"></iframe>

答案 1 :(得分:1)

首先,您必须防止单击锚点触发的默认操作。为此,请使用事件对象并调用以下方法:

event.preventDefault();

然后将元素传递到触发事件的switchIframeSrc

switchIframeSrc(event.target);


var switcher$ = $('.switcher');
var switchTarget$ = $('.switch-target');

switcher$.on('click', event => {
  event.preventDefault();
  switchIframeSrc(event.target);
});

function switchIframeSrc(anchor) {
  switchTarget$.attr('src', $(anchor).attr('href'));
}

// call the method on load
switchIframeSrc();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="switcher">
  <a href ="https://codepen.io/shawkdsn/pen/rLIgC">Option 1</a>
  <a href ="https://codepen.io/shawkdsn/pen/ejBJw">Option 2</a>
</div>

<iframe class="switch-target" width="300" height="300" src=""></iframe>