使用 querySelectorAll select 所有匹配 document.URL 的 href?
Using querySelectorAll to select all href that matches document.URL?
我尝试在 href 与文档的 URL 匹配时添加 class 使用:
<script>
currentLinks = document.querySelectorAll('a[href="'+document.URL+'"]')
currentLinks.forEach(function(link) {
link.className += ' current-link'
});
</script>
但是,我卡在了第一行,因为它 returns 是一个空的节点列表。
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"]
作为 returns 完整路径?
您的 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.
的路径名部分
我尝试在 href 与文档的 URL 匹配时添加 class 使用:
<script>
currentLinks = document.querySelectorAll('a[href="'+document.URL+'"]')
currentLinks.forEach(function(link) {
link.className += ' current-link'
});
</script>
但是,我卡在了第一行,因为它 returns 是一个空的节点列表。
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"]
作为 returns 完整路径?
您的 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.