我想這是指$("#countdown").text(...)
。你每秒鐘運行一次相同的選擇器。
將它緩存在一個變量中並以這種方式引用它會更有效。
var seconds = 20;
var $countdown; // variable to store #countdown.
// Initialized here so it is in scope of updateCountdown()
function updateCountdown() {
if (seconds === 0) {
document.forms[0].submit();
} else {
// reference the #countdown element stored in the variable
$countdown.text("Refresh: " + seconds);
seconds = seconds - 1;
}
}
jQuery(function($) {
// Once document is ready, find the #countdown element, and cache it
$countdown = $('#countdown');
setInterval("updateCountdown()",1000);
});
而且,可以說,這是更好/更有效的將updateCountdown
函數的命名引用傳遞給setInterval()
而不是字符串。
setInterval(updateCountdown,1000);
而且,好像你清除setInterval()
一次seconds
達到0
它不會出現。可能是一個好主意。
var seconds = 20;
var $countdown; // variable to store #countdown.
// Initialized here so it is in scope of updateCountdown()
var interval; // store reference to the setInterval()
function updateCountdown() {
if (seconds === 0) {
document.forms[0].submit();
// clear the setInterval
clearInterval(interval);
} else {
// reference the #countdown element stored in the variable
$countdown.text("Refresh: " + seconds);
seconds = seconds - 1;
}
}
jQuery(function($) {
// Once document is ready, find the #countdown element, and cache it
$countdown = $('#countdown');
// retain reference to the setInterval call
interval = setInterval(updateCountdown,1000);
});
從效率的角度來看,這是一個很好的建議,但如果jQuery.lint正在做這種分析,我會留下深刻的印象。沒有使用jQuery.lint,我猜測它是在做靜態分析,而不是運行時分析,這對於描述你描述的情況是必要的(或者我錯了)。如果菲利普報告說這個建議可以解決他的問題,那麼我會認爲自己「印象深刻」。 – belugabob 2010-08-09 14:49:05
@belugabob - 這是一個簡單的測試(打開您的控制檯查看)。 http://jsfiddle.net/DPcjK/看起來,這正是jQuery Lint正在做的事情。如果修改示例以緩存選擇器,則警告消失。 – user113716 2010-08-09 14:59:52
緩存選擇器工作!感謝Patrick! http://pastebin.com/5YzE81v4 – 2010-08-09 20:52:45