使用 HTML select 下拉列表更新 iframe 的 src 路径

Updating src path of an iframe using a HTML select dropdown

我正在尝试使用 HTML 表单元素(特别是 select 下拉列表)来更新页面中嵌入的 iframe 的 URL 路径。每次创建不同的 selection 时都应该重新加载 iframe。

我已经尝试使用 Javascript 函数在 onkeyup 或 onmouseup 事件发生时传递 select 的值,但我没有看到发生这种情况时发生任何变化:

<!DOCTYPE html>

<head>

<style>

* {font-family: arial;}

</style>
<script type="text/javascript">

window.onload = function() {
  document.monthyear.onkeyup = my;
  document.monthyear.onmouseup = my;

};

function my() {

var my = String(document.monthyear.value);

document.getElementById("iframe").src = my;

};

</script>

</head>

<body>

<select name="monthyear">
    <option value="/258001">
        January 2019
    </option>
    <option value="/258002">
        February 2019
    </option>
    <option value="/258003">
        March 2019
    </option>
    <option value="/258004">
        April 2019
    </option>
</select>

<h1>Month</h1><iframe allowfullscreen frameborder="0" height="450" id="iframe" src="https://www.example.com/258001" style="border:0" width="800"></iframe>

使用selected属性设置select标签的默认值,然后(见代码注释)...

<script>
const select = document.querySelector('#select')
window.onload = function() {
  // set the iframe value to default select value
  document.getElementById("iframe").src = '/258001'
};
// add an event listener that listens for a change to the input and sets the iframe path.
select.addEventListener('change', (e) => {
 document.getElementById("iframe").src = e.target.value
document.getElementById("iframe").contentWindow.location.reload()
})

</script>

</head>

<body>

<select id="select" name="monthyear">
    <option value="/258001" selected="selected">
        January 2019
    </option>
    <option value="/258002">
        February 2019
    </option>
    <option value="/258003">
        March 2019
    </option>
    <option value="/258004">
        April 2019
    </option>
</select>

<h1>Month</h1><iframe allowfullscreen frameborder="0" height="450" id="iframe" src="https://www.example.com/258001" style="border:0" width="800"></iframe>

试试这样使用:

 <select onchange='this.options[this.selectedIndex].value && (window.location = this.options[this.selectedIndex].value);'>
  <a href='#'><option>choose an action</option></a>
  <option value='Url or div'>Option 1</option>
  <option value='Url or div'>Option 2</option>

  </select>