2014-01-22 3 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'을 작성했기 때문에 예상대로 작동하지 않습니다. 글로벌'i' 변수를 사용하려면'var'을 제거하십시오. –

+2

은 익명 함수 내에서'var i = 1'의'var'을 가져옵니다. 즉, 익명 함수 내에서'i'라는 지역 변수를 생성하게됩니다. –

답변

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 
    } 

}); 
관련 문제