以下代码仅在选择下拉列表时刷新iframe。这很好,但只有在有人改变初始值时才会开始。
我试图在父页面加载到默认值1分钟时启动它,除非该值已被更改。
因此,如果页面加载时默认值为1分钟,则用户选择5分钟然后刷新父页面,将显示5分钟,并自动从该选择开始计时器。但是如果用户第一次加载父页面,则会显示1分钟并启动计时器。
我已尝试加载onload函数,但我无法让它工作。
<!DOCTYPE html>
<html>
<head>
<title>refresh</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
var interval = 0;
var auto_refresh = 0;
$(document).ready(function() {
$('#reload_interval').change(function() {
var reload = $(this).val();
interval = reload * 1000;
if (auto_refresh) {
clearInterval(auto_refresh);
}
if (reload) {
auto_refresh = setInterval(function() {
// function to run
document.getElementById('iframe').contentWindow.location.reload();
//
}, interval);
}
});
});
</script>
</head>
<body>
<select id="reload_interval">
<option></option>
<option value='10'>10 sec</option>
<option value='30'>30 sec</option>
<option value='60'>1 min</option>
<option value='300'>5 min</option>
<option value='600'>10 min</option>
</select>
<br><br>
<iframe id="iframe" name="iframe" src="test.html" style="border-style: none; border:0px; background-color:transparent;" frameborder="0" width="743" height="300"></iframe>
</body>
</html>
答案 0 :(得分:0)
要使所选值保持不变,您必须将该值存储在某处,因此我选择localStorage。看看下面的代码,它应该做你要求的所有事情,并指出一些注意事项。
<!DOCTYPE html>
<html>
<head>
<title>refresh</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(function (){
// Set interval from localStorage or set it to 1 minute.
var interval = localStorage.interval ? localStorage.interval : 60000;
var autoRefresh;
// Separate function for setting interval to keep things clean.
var setter = function (val) {
var currentInterval = setInterval(function () {
$('iframe').attr('src', 'test.html');
}, val);
return currentInterval;
}
// Create our handler function for the change event.
$('#reload_interval').change(function () {
// Update interval & localStorage.interval values
interval = $(this).val() * 1000;
localStorage.interval = interval;
// Clear our old interval and/or set the new one
if (autoRefresh) { clearInterval(autoRefresh); }
autoRefresh = setter(interval);
});
// Set the <select> tag value
$('#reload_interval').val(localStorage.interval / 1000);
// Fire the change event to set things going.
$('#reload_interval').trigger('change');
});
</script>
</head>
<body>
<select id="reload_interval">
<option></option>
<option value='10'>10 sec</option>
<option value='30'>30 sec</option>
<option value='60'>1 min</option>
<option value='300'>5 min</option>
<option value='600'>10 min</option>
</select>
<br><br>
<iframe id="iframe" name="iframe" src="test.html" style="border-style: none; border:0px; background-color:transparent;" frameborder="0" width="743" height="300"></iframe>
</body>
</html>