Javascript JavasScript—;未捕获错误:语法错误,无法识别的表达式:[href=#contact](WordPress)
我正在尝试实现一种交互,在这种交互中,当视图中有一个类时,会将一个类添加到一个特定的菜单项中。不幸的是,我遇到以下错误:Javascript JavasScript—;未捕获错误:语法错误,无法识别的表达式:[href=#contact](WordPress),javascript,jquery,scroll,menu,interaction,Javascript,Jquery,Scroll,Menu,Interaction,我正在尝试实现一种交互,在这种交互中,当视图中有一个类时,会将一个类添加到一个特定的菜单项中。不幸的是,我遇到以下错误: Uncaught Error: Syntax error, unrecognised expression: [href=#contact] 先谢谢你 伪码 滚动页面 当区段处于视图中时,向相应的导航项目添加一个类 JavaScript // Cache selectors var lastId, topMenu = $('#top-menu'), to
Uncaught Error: Syntax error, unrecognised expression: [href=#contact]
先谢谢你
伪码
- 滚动页面
- 当区段处于视图中时,向相应的导航项目添加一个类
// Cache selectors
var lastId,
topMenu = $('#top-menu'),
topMenuHeight = topMenu.outerHeight() + 1,
// All list items
menuItems = topMenu.find('a'),
// Anchors corresponding to menu items
scrollItems = menuItems.map(function() {
var item = $($(this).attr('href'))
if (item.length) {
return item
}
})
// Bind click handler to menu items
// so we can get a fancy scroll animation
menuItems.click(function(e) {
var href = $(this).attr('href'),
offsetTop = href === '#' ? 0 : $(href).offset().top - topMenuHeight + 1
$('html, body').stop().animate(
{
scrollTop: offsetTop,
},
850,
)
e.preventDefault()
})
// Bind to scroll
$(window).scroll(function() {
// Get container scroll position
var fromTop = $(this).scrollTop() + topMenuHeight
// Get id of current scroll item
var cur = scrollItems.map(function() {
if ($(this).offset().top < fromTop) return this
})
// Get the id of the current element
cur = cur[cur.length - 1]
var id = cur && cur.length ? cur[0].id : ''
console.log('Cur', cur, 'ID', id)
if (lastId !== id) {
lastId = id
// Set/remove active class
menuItems.parent().removeClass('active').end().filter('[href=#' + id + ']').parent().addClass('active')
}
})
//缓存选择器
var lastId,
topMenu=$(“#top menu”),
topMenuHeight=topMenu.outerHeight()+1,
//所有列表项
menuItems=topMenu.find('a'),
//与菜单项相对应的锚定
scrollItems=menuItems.map(函数(){
var item=$($(this.attr('href'))
如果(项目长度){
退货项目
}
})
//将单击处理程序绑定到菜单项
//所以我们可以得到一个奇特的卷轴动画
菜单项。单击(函数(e){
var href=$(this.attr('href'),
offsetTop=href=='#'?0:$(href).offset().top-topMenuHeight+1
$('html,body').stop().animate(
{
scrollTop:offsetTop,
},
850,
)
e、 预防默认值()
})
//绑定到滚动
$(窗口)。滚动(函数(){
//获取容器滚动位置
var fromTop=$(this).scrollTop()+topMenuHeight
//获取当前滚动项目的id
var cur=scrollItems.map(函数(){
if($(this).offset().top
jQuery在属性选择器中使用引号时非常挑剔。必须为该值(单或双)提供一个带引号的字符串
更改:
filter('[href=#' + id + ']')
filter('[href="#' + id + '"]')
至:
filter('[href=#' + id + ']')
filter('[href="#' + id + '"]')
如果您想稍微不那么精确,但有放弃
#
的好处,您可以使用~=
,而不仅仅是=
。jQuery在属性选择器中使用引号时非常挑剔。必须为该值(单或双)提供一个带引号的字符串
更改:
filter('[href=#' + id + ']')
filter('[href="#' + id + '"]')
至:
filter('[href=#' + id + ']')
filter('[href="#' + id + '"]')
如果您想稍微不那么精确,但有助于删除
#
,您可以使用~=
,而不仅仅是=
。Randy Casbum感谢您的帮助。您的解决方案解决了问题。Randy Casbum感谢您的帮助。你的解决方案解决了这个问题。