你不止一次使用过同一个选择器 [英] You've used the same selector more than once
问题描述
为什么jQuery.lint.js说我多次使用同一个选择器?
Why is jQuery.lint.js saying that I've used the same selector more than once?
这是我的代码:
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
选择器:#count
推荐答案
我猜它是指 $(#countdown)。text(...)
。你每秒运行一次相同的选择器。
I would guess it is referring to $("#countdown").text(...)
. You're running that same selector once every second.
将它缓存在一个变量中并以这种方式引用它会更有效。
It would be more efficient to cache it in a variable, and reference it that way.
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);
});
此外,可以认为传递<的命名参考更好/更有效率code> updateCountdown 函数到 setInterval()
而不是字符串。
Also, it could be argued that it is better/more efficient to pass the named reference of the updateCountdown
function to the setInterval()
instead of a String.
setInterval(updateCountdown,1000);
此外,它看起来并不像你在秒
到达 0
时,清除 setInterval()
。可能是个好主意。
Also, it doesn't appear as though you're clearing your setInterval()
once seconds
reaches 0
. Probably a good idea.
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);
});
这篇关于你不止一次使用过同一个选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!