使用特定 class 滚动到特定标签名称

Scroll to specific tag name with specific class

我的 html 代码如下所示:

<div class="code">
    <declaration class="2">
        toto
    </declaration>
    <identifier class="2">
        toto
    </identifier>
    <identifier class="3">
        toto
    </identifier>
    <identifier class="2">
        toto
    </identifier>
</div>

这是我的 javascript :

function gotoDeclaration(){
    $(".code identifier").click(function goto() {
        var list = document.getElementsByClassName($(this).attr('class'));
        for (var i = 0; i < list.length; i++) {
            if (list[i].nodeName === 'declaration')
                $('html, body').animate(
                    {scrollTop: list[i].offset().top}, 
                    'fast');
            return false;
        }
    });
}

我想做的是,如果我点击带有标签名称标识符的元素,它会滚动到带有标签名称声明的元素,与标识符元素相同class。

点击时没有任何反应。

该函数与其他一些工作函数一起被调用:

$(document).ready(function(){
gotoDeclaration();
highlightIdentifiers();
expandCollapse();
});

list[i] return 一个 HTML 元素。问题是您正在使用 jQuery 函数:list[i].offset().

要解决这个问题,请改用 .eq

$('html, body').animate(
    {scrollTop: list.eq(i).offset().top}, 
    'fast');

还有一种更好的编码方式。由于jQuery已经加载,使用它!

function gotoDeclaration(){
    $(".code identifier").click(function goto() {
        var list = $('declaration.'+$(this).attr('class'));
        $('html, body').animate(
             {scrollTop: list.offset().top}, 
             'fast');
    });
}

为什么要遍历所有元素? 你不需要所有这些只是为了一个简单的任务。

试试这个:

function gotoDeclaration(){
    $(".code identifier").click(function goto() {
        var $dec = $('declaration.'+$(this).attr('class'));
        $('html, body').animate({scrollTop: $dec.offset().top}, 'fast');
    });
}


$(document).ready(function(){
  gotoDeclaration();
});
identifier,
declaration { height:400px; display:block; }
identifier { background-color:lightblue; cursor:pointer; }
declaration { background-color:lightgreen; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="code">
    <declaration class="2">
        declaration 2
    </declaration>
    <identifier class="2">
        identifier 2
    </identifier>
    <declaration class="3">
        declaration 3
    </declaration>
    <identifier class="3">
        identifier 3
    </identifier>
</div>