【发布时间】:2018-08-31 21:42:19
【问题描述】:
当 href 匹配文档的 URL 时,我正在尝试添加一个类:
<script>
currentLinks = document.querySelectorAll('a[href="'+document.URL+'"]')
currentLinks.forEach(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"],因为它会返回完整路径?
【问题讨论】:
-
你有没有把这个脚本放在文档末尾?
-
是的,在身体关闭之前
-
+不是选择器的一部分。它是字符串连接运算符。'a[href="'document.URL'"]'是一个语法错误。 -
只有在您拥有完整的绝对 href 时才有效。如果使用相对的,你将不得不遍历所有
a -
考虑到您的上次编辑,
location.pathname(而不是document.URL)可能就是您要查找的内容。不过,您可能必须剪掉尾随的/。
标签: javascript jquery jquery-selectors