2010-08-09 36 views
2

爲什麼jQuery.lint.js說我多次使用同一個選擇器?您已經多次使用相同的選擇器

這裏是我的代碼:

var seconds = 20; 

function updateCountdown() { 
    if (seconds === 0) { 
     document.forms[0].submit(); 
    } else { 
     $("#countdown").text("Refresh: " + seconds); 
     seconds = seconds - 1; 
    } 
} 

jQuery(function($) { 
    setInterval("updateCountdown()",1000); 
}); 

它說:

地點:

@http://localhost/js/SubmitForm_Countdown.js:7

@http://localhost/js/SubmitForm_Countdown.js:13

選擇: 「#countdown」

回答

5

我想這是指$("#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); 
}); 
+0

從效率的角度來看,這是一個很好的建議,但如果jQuery.lint正在做這種分析,我會留下深刻的印象。沒有使用jQuery.lint,我猜測它是在做靜態分析,而不是運行時分析,這對於描述你描述的情況是必要的(或者我錯了)。如果菲利普報告說這個建議可以解決他的問題,那麼我會認爲自己「印象深刻」。 – belugabob 2010-08-09 14:49:05

+1

@belugabob - 這是一個簡單的測試(打開您的控制檯查看)。 http://jsfiddle.net/DPcjK/看起來,這正是jQuery Lint正在做的事情。如果修改示例以緩存選擇器,則警告消失。 – user113716 2010-08-09 14:59:52

+0

緩存選擇器工作!感謝Patrick! http://pastebin.com/5YzE81v4 – 2010-08-09 20:52:45

相關問題