Jquery 你';我不止一次使用同一个选择器
为什么jQuery.lint.js说我不止一次使用同一个选择器 这是我的密码:Jquery 你';我不止一次使用同一个选择器,jquery,Jquery,为什么jQuery.lint.js说我不止一次使用同一个选择器 这是我的密码: var seconds = 20; function updateCountdown() { if (seconds === 0) { document.forms[0].submit(); } else { $("#countdown").text("Refresh: " + seconds); seconds = seconds - 1;
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);
});
它说:
地点:
@
@
选择器:“#倒计时”我猜它指的是
$(“#倒计时”).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,我猜它是在做静态分析,而不是运行时分析,这对于捕捉您描述的情况是必要的(或者我错了)。如果菲利浦报告该建议修正了他的问题,那么我会认为自己是“印象深刻的”。@ Belgabb-这是一个简单的测试(打开你的控制台查看)。似乎jQuery Lint正是这么做的。如果修改示例以缓存选择器,警告将消失。Patrick-正如承诺的那样,我印象深刻。现在我需要亲自研究jQuery.lint的使用。谢谢你的信息。