网页滚动后URL出现#[object Object]异常问题求助
问题:点击导航滚动后URL末尾出现#[object%20Object]
点击导航栏的li元素时,页面能正常滚动到对应板块,但URL末尾附加的是/#[object Object]而非预期的/#inscripcion这类正确哈希值。
相关代码
index.html
<ul class="nav"> <li class="scroll-to-section"><a href="#inscripcion">Inscripciones</a></li> <li class="scroll-to-section"><a href="#recorridos">Recorridos</a></li> <li class="scroll-to-section"><a href="#schedule">Reglamento</a></li> <li class="scroll-to-section"><a href="#contact">Contacto</a></li> <li class="scroll-to-section"></li> </ul> <!-- ***** Code to scroll ***** --> <section class="section" id="inscripcion">
custom.js
$(document).ready(function () { $(document).on("scroll", onScroll); //smoothscroll $('.scroll-to-section a[href^="#"]').on('click', function (e) { e.preventDefault(); $(document).off("scroll"); $('a').each(function () { $(this).removeClass('active'); }) $(this).addClass('active'); var target = this.hash, menu = target; var target = $(this.hash); console.log(target); $('html, body').stop().animate({ scrollTop: (target.offset().top) + 1 }, 500, 'swing', function () { window.location.hash = target; console.log(window.location.hash); $(document).on("scroll", onScroll); }); }); }); function onScroll(event){ var scrollPos = $(document).scrollTop(); $('.nav a').each(function () { var currLink = $(this); var refElement = $(currLink.attr("href")); if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) { $('.nav ul li a').removeClass("active"); currLink.addClass("active"); } else{ currLink.removeClass("active"); } }); }
问题原因
代码里重复声明了target变量:
- 第一行
var target = this.hash获取的是正确的哈希字符串(比如#inscripcion) - 第二行
var target = $(this.hash)把它转换成了jQuery对象
之后在动画回调里给window.location.hash赋值了这个jQuery对象,JavaScript会自动把对象转成字符串[object Object],导致URL出现异常。
解决方案
保留原始的哈希字符串变量,将jQuery对象重命名为其他变量(比如$target),在对应场景使用正确的变量:
修改后的custom.js关键部分:
//smoothscroll $('.scroll-to-section a[href^="#"]').on('click', function (e) { e.preventDefault(); $(document).off("scroll"); $('a').each(function () { $(this).removeClass('active'); }) $(this).addClass('active'); var target = this.hash, menu = target; var $target = $(this.hash); // 重命名为$target区分jQuery对象 console.log($target); $('html, body').stop().animate({ scrollTop: ($target.offset().top) + 1 // 使用$target获取元素位置 }, 500, 'swing', function () { window.location.hash = target; // 这里用原始的target字符串设置哈希 console.log(window.location.hash); $(document).on("scroll", onScroll); }); });
修改后,点击导航时URL会正确显示对应的哈希值,滚动功能保持正常。
内容的提问来源于stack exchange,提问作者SERGIO GARCÍA GONZÁLEZ
相关产品推荐
相关产品推荐

