开发者

You've used the same selector more than once

Why is jQuery.lint.js saying that I've used the same selector more than once?

Here's my code:

var seconds = 20;

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

jQuery(function($开发者_JAVA百科) {
   setInterval("updateCountdown()",1000);
});

It's saying:

Location:

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

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

Selector: "#countdown"


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

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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜