Javascript for循环来导航节

javascript for loop to navigate sections

本文关键字:导航 循环 for Javascript      更新时间:2023-09-26

我试图使用for循环创建导航,在actionscript中我通常使用for循环来做到这一点。我想给每个链接分配相同的动作(scrollTop),但有不同的目标(#sec1, #sec2…)。但是在javascript中,我不明白我错在哪里。

一个例子:

var Secs = [
    "sec1",
    "sec2",
    "sec3",
    "sec4",
    "sec5",
    "sec6"
];
for(var i = 0; i < Secs.length; i++){
    $("." + this.Secs).click(function(){
        $('html, body').animate({scrollTop: $("#" + this.Secs).offset().top}, 700);
    });
}

Thx .

你不能使用this.Secs - 因为Secs是一个数组你可以像这样使用Secs[i]

 $("." + Secs[i]).click(function(){
        $('html, body').animate({scrollTop: $("#" + Secs[i]).offset().top}, 700);
 });