![](/img/trans.png)
[英]Use value from dropdown to set setInterval var in Javascript
[英]Use value from dropdown to set setInterval with jQuery change
我正在嘗試一個下拉菜單,該菜單可讓用戶選擇頁面刷新的頻率。 我在$(document).ready()中有以下代碼:
$(".refreshInterval").change( setInterval( showDashboard(),parseFloat( $(".refreshInterval").val() )*60*1000) );
... refreshInterval是...
<select class="refreshInterval" value="1">
<option value="0">Off</option>
<option value="0.5" selected>30 sec</option>
<option value="1">1 min</option>
<option value="2">2 min</option>
<option value="5">5 min</option>
</select>
並且showDashboard()
是可訪問的函數。 初始加載頁面時,將調用showDashboard()
。 但是,當我更改下拉菜單時,我從jQuery收到此錯誤:
Uncaught TypeError: Object 166 has no method 'apply'
任何想法?
我建議您以更清晰的方式編寫代碼(而不是單行代碼)。 這樣更容易發現語法錯誤。
解決方案:( 不好,請檢查編輯! )
$(".refreshInterval").change(function() {
var interval = parseFloat( $(this).val() ) * 60 * 1000;
setInterval(showDashboard(), interval)
});
你不見了
function() { }
編輯--------
不好意思! 我放
setInterval(showDashboard(), interval)
應該是
setInterval(showDashboard, interval);
這是正確的完整代碼:
ref = setInterval(showDashboard, 1000)
$(".refreshInterval").change(function() {
var interval = parseFloat( $(this).val() ) * 60 * 1000;
clearInterval(ref);
console.log("New Interval: " + interval);
if (interval > 0) {
ref = setInterval(showDashboard, interval)
}
});
function showDashboard() {
console.log(Math.random());
}
和jsFiddle: http : //jsfiddle.net/xkj43/3/
嘗試這個:
$(".refreshInterval").change(function(){
setInterval(showDashboard,parseFloat($(".refreshInterval").val())*60*1000)
});
您需要將一個函數傳遞給事件。.您正在這里傳遞一個方法。
同時將此showDashboard()
更改為showDashboard
嘗試一下
$(".refreshInterval").change(function(){
setInterval(showDashboard,parseFloat($(".refreshInterval").val())*60*1000))
});
指出需要將函數傳遞給setInterval
的其他答案是正確的。
但是,您為每個變更呼叫設置了一個新間隔,而不會清除舊的呼叫,因此,如果有人選擇“ 1”然后選擇“ 5”,則每5分鍾將有6次呼叫到showDashboard
。 您需要捕獲間隔ID並在每次新的setInterval
調用之前將其清除。
$(function() {
var dashboardRefreshInterval;
$(".refreshInterval").change(function(){
clearInterval(dashboardRefreshInterval);
dashboardRefreshInterval = setInterval(showDashboard,parseFloat($(".refreshInterval").val())*60*1000))
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.