你不止一次使用过同一个选择器

为什么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

选择器:“#countt”

我猜它是指$("#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()而不是String更好/更有效。

  setInterval(updateCountdown,1000); 

此外,一旦seconds达到0 ,它似乎不会清除setInterval() 。 可能是个好主意。

 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); });