我正在尝试使用HTML表单元素(特别是选择下拉列表)来更新嵌入在页面上的iframe的URL路径。每次进行其他选择时,都应该重新加载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>
尝试这样使用:
<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 id'>Option 1</option>
<option value='Url or div id'>Option 2</option>
</select>
使用selected
属性设置选择标签的默认值,然后(请参见代码中的注释)...
<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>