我有一个简单的增量计数器设置,它控制页面上的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 :(得分: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
}
});