JavasScript — Uncaught Error: Syntax error, unrecognised expression: [href=#contact] (WordPress)

JavasScript — Uncaught Error: Syntax error, unrecognised expression: [href=#contact] (WordPress)

我正在尝试实现一种交互,其中 class 在视图中添加到特定菜单项。不幸的是,我收到以下错误:

Uncaught Error: Syntax error, unrecognised expression: [href=#contact]

提前谢谢你。

伪代码

JavaScript

// 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')
    }
})

jQuery 对于属性选择器中的引号非常挑剔。您必须为值(单引号或双引号)提供带引号的字符串。

变化:

filter('[href=#' + id + ']')

收件人:

filter('[href="#' + id + '"]')

如果您想要稍微不那么精确,但又想去掉 #,您可以使用 ~= 而不是 =