javascript - JavaScript — 未捕获错误 : Syntax error, 无法识别的表达式:[href=#contact] (WordPress)

标签 javascript jquery scroll menu interaction

我正在尝试实现一种交互,其中当 a 处于 View 中时,将类添加到特定菜单项。不幸的是,我收到以下错误:

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

提前谢谢您。

伪代码

  • 滚动页面
  • 当该部分处于 View 中时,向相应的导航项添加一个类

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 非常挑剔。您必须使用带引号的字符串作为值(单精度或 double )。

更改:

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

致:

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

如果您想要稍微不那么精确,但又可以删除 #,您也可以使用 ~= 而不仅仅是 = .

关于javascript - JavaScript — 未捕获错误 : Syntax error, 无法识别的表达式:[href=#contact] (WordPress),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53438387/

相关文章:

javascript - HTML5 History API 需要双击后退

javascript - 如果鼠标离开父元素则隐藏元素

javascript - 打开模式时防止 BODY 滚动

Android - TabWidget 的编程滚动

javascript - jQuery.DataTables - fnAddData 不起作用

javascript - react Hook : Set state 'ModalVisible' but state does not update immediately

javascript - 制作 ng-donut 可点击的 AngularJs

javascript - 显示所有key未知的本地存储

jquery - 有没有办法在 jQuery 中左右滑动而不使用 jQuery UI 和 jQuery Mobile

jquery - 是否可以使用按键(PgUp、PgDn、...空格键?...)来控制可滚动的 jquery ui 对话框