You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

锚点滚动功能异常:遍历对象未返回匹配项却返回最后一项

问题说明

这段代码原本想实现:点击带有.scrollToPosition类的锚点链接时,滚动到对应ID的标题元素(锚点格式类似#titles)。但实际运行时,无法正确找到目标滚动元素,反而返回了对象的最后一项。

原错误代码

$('.scrollToPosition').click(function (e) {
    e.preventDefault();

    url = $(this).attr("href"); //获取链接地址
    console.log(url);

    linkid = url.substring(url.lastIndexOf("#") + 1); //解析出ID部分
    console.log('linkid =' + linkid, linkid.length);

    linkTarget = $('.scrollTarget').find($('a').attr("id") === linkid);

    destinations = linkTarget.prevObject;

    destinations.each(function (i) {
        scrollTo = $(this).find( $('#' + currentLink) === [i]);
        console.log(i)
        return
    })
})

问题根源

  1. 元素选择逻辑完全错误:$('.scrollTarget').find($('a').attr("id") === linkid)中,$('a').attr("id") === linkid是一个布尔值,jQuery会把它当作字符串去查找元素,自然找不到匹配项。
  2. 未定义变量currentLink,且$('#' + currentLink) === [i]的比较逻辑毫无意义,无法定位目标元素。
  3. 错误使用prevObject,这是jQuery内部属性,不应该用来获取元素集合。

修正后的代码

直接通过解析出的linkid定位目标元素,调用scrollIntoView实现滚动:

$('.scrollToPosition').click(function (e) {
    e.preventDefault();
    
    // 获取锚点中的ID部分
    const linkId = $(this).attr("href").split("#")[1];
    // 直接定位对应ID的元素
    const targetElement = document.getElementById(linkId);
    
    if (targetElement) {
        // 平滑滚动到目标元素
        targetElement.scrollIntoView({ behavior: 'smooth', block: 'start' });
    } else {
        console.warn(`未找到ID为${linkId}的元素`);
    }
})

如果目标元素必须在.scrollTarget容器内查找,可修改为:

$('.scrollToPosition').click(function (e) {
    e.preventDefault();
    
    const linkId = $(this).attr("href").split("#")[1];
    // 在.scrollTarget容器内查找对应ID的元素
    const targetElement = $('.scrollTarget').find(`#${linkId}`)[0];
    
    if (targetElement) {
        targetElement.scrollIntoView({ behavior: 'smooth', block: 'start' });
    } else {
        console.warn(`未找到ID为${linkId}的元素`);
    }
})

内容的提问来源于stack exchange,提问作者Reante Marrel Patterson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 18:35:13