【问题标题】:Using querySelectorAll to select all href that matches document.URL?使用 querySelectorAll 选择与 document.URL 匹配的所有 href?
【发布时间】:2018-08-31 21:42:19
【问题描述】:

当 href 匹配文档的 URL 时,我正在尝试添加一个类:

<script>
    currentLinks = document.querySelectorAll('a[href="'+document.URL+'"]')
    currentLinks.forE‌​ach(function(link) {
        link.className += ' current-link'
    });
</script>

但是,我被困在第一行,因为它返回一个空节点列表。

document.querySelectorAll('a[href="'+document.URL+'"]')

HTML

<li role="presentation" class="current nav-level-5 nav-entry-1 list-position-1  links-open"><a id="perc-navigation-menuitem-nav-level-5-nav-entry-1-list-position-1-113428783" href="/-training-test/menu-test/sub-menu-1/another-level-1/" role="menuitem">Another Level 1</a></li>

另外,+document.URL+ 中的下一个选择器 (+) 有什么用?为什么不直接使用a[href="document.URL"],因为它会返回完整路径?

Link

【问题讨论】:

  • 你有没有把这个脚本放在文档末尾?
  • 是的,在身体关闭之前
  • + 不是选择器的一部分。它是字符串连接运算符。 'a[href="'document.URL'"]' 是一个语法错误。
  • 只有在您拥有完整的绝对 href 时才有效。如果使用相对的,你将不得不遍历所有 a
  • 考虑到您的上次编辑,location.pathname(而不是 document.URL)可能就是您要查找的内容。不过,您可能必须剪掉尾随的/

标签: javascript jquery jquery-selectors


【解决方案1】:

HTML 中的href 属性是/-training-test/menu-test/sub-menu-1/another-level-1/。但是document.URL 是一个完全限定的 URL,类似于http://www.yourdomain/com/-training-test/menu-test/sub-menu-1/another-level-1/,所以href 与此不完全匹配。

尝试使用location.pathname,而不是document.URL,它只是URL 的路径名部分。

【讨论】:

    猜你喜欢
    • 2021-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-01
    • 2016-11-22
    • 2013-05-19
    • 1970-01-01
    • 2020-10-14
    相关资源
    最近更新 更多