为什么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”
答案 0 :(得分: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);
});
。可能是一个好主意。
{{1}}