2014-01-22 124 views
-1

我有一個簡單的增量計數器設置,它控制頁面上的href值,每次點擊並更新它。然而,當被訪問頁面上的最後一節,我要到櫃檯重置回1.重置計數器增量

var firstSectionID = $('body .each-section').eq(1).attr('id'); 
$('.next-section').attr("href", '#' + firstSectionID); 

var i = 1; 
$('.next-section').click(function() { 

    var nextSectionID = $('body .each-section').eq(i).attr('id'); 
    i++; 
    $('.next-section').attr('href', '#' + nextSectionID); 

    var numberOfSections = $('body .each-section').length; 
    var lastSectionID = $('body .each-section').eq(numberOfSections).attr('id'); 

    if ($('.next-section').attr('href') == '#' + lastSectionID) { 
     $('.next-section').attr('href', '#' + firstSectionID); 
     alert('last'); 
      //var i = 1; // I thought adding this would work, but it breaks the code after the first click 
    } 

}); 

任何想法原值?

+0

「但它打破了第一次點擊後的代碼」 休息怎麼樣?什麼是錯誤? –

+0

可能不會像你期望的那樣工作,因爲你寫了'var i'。嘗試刪除'var'以使用全局變量'i'。 –

+2

在匿名函數中將'var'從'var i = 1'中取出。這導致它在匿名函數 –

回答

1

刪除VAR:

var firstSectionID = $('body .each-section').eq(1).attr('id'); 
$('.next-section').attr("href", '#' + firstSectionID); 

var i = 1; 
$('.next-section').click(function() { 

    var nextSectionID = $('body .each-section').eq(i).attr('id');//*0* eq(undefined) --> fail 
    i++;//*1* become undefined++ --> NaN 
    $('.next-section').attr('href', '#' + nextSectionID); 

    var numberOfSections = $('body .each-section').length; 
    var lastSectionID = $('body .each-section').eq(numberOfSections).attr('id'); 

    if ($('.next-section').attr('href') == '#' + lastSectionID) { 
     $('.next-section').attr('href', '#' + firstSectionID); 
     alert('last'); 
     i = 1; //*2* if you init i here like var i, on lines *0* and *1* it will be undefined 
    } 

});