[英]Adding active class based on current URL
我正在尝试在我的链接上添加“活动”类。 它在说
Uncaught TypeError: document.querySelectorAll(...).each is not a function
这是我的代码:
const current = window.location.href;
document.querySelectorAll("#nav-tab a").each(function(){
const $this = this;
if($this.attr('href').indexOf(current) !== -1){
$this.classList.add("active");
}
});
你能帮助我吗? 或者有没有更好的方法来添加基于当前 URL 的类名? 太感谢了!
我认为你误会了 jQuery 和 vanilla javascript
$.each是一个 jQuery 函数,你可以使用.forEach
$.attr是一个jQuery函数,你可以使用.getAttribute
const current = "#test-3";//window.location.href; document.querySelectorAll("#nav-tab a").forEach((elem) => { if (elem.getAttribute('href').indexOf(current) !== -1) { elem.classList.add("active"); } });
.active { color:red}
<div id="nav-tab"> <a href="#test-1">Test 1</a> <a href="#test-2">Test 2</a> <a href="#test-3">Test 3</a> <a href="#test-4">Test 4</a> </div>
您的代码有一些问题。 您主要将 jQuery 方法与常规的本机浏览器方法/约定混淆:
您需要使用.forEach()
而不是.each()
。 .forEach()
方法是NodeList上querySelectorAll()
返回的方法。
.attr()
不是有效的方法。 要获取元素的属性,您可以使用.getAttribute()
。 我们可以在这里使用.href
来获取 href。 请注意, getAttribute("href")
将检索标记中的 URL,而.href
将检索完整的,例如,如果您有href="/foo/bar"
, .href
将给出https://example.com/foo/bar
,而.getAttribute()
将只返回/foo/bar
。
使用函数的元素参数而不是this
。 当您使用.forEach()
时,您正在迭代 NodeList 中的元素(即:您选择的元素),因此您可以使用forEach
回调的第一个参数访问每个元素。 浏览器中的this
值(如果不是在严格模式下)将默认为window
,因此它不会是您期望的元素:
const current = window.location.href;
document.querySelectorAll("#nav-tab a").forEach(function(elem){
if(elem.href.includes(current)){
elem.classList.add("active");
}
});
我还将.indexOf(...) !== -1
更改为.includes()
,这是一种更现代的检查字符串是否包含另一个值的方法。
我会指出,您可以使您的查询选择器更高级,这将限制您迭代的元素数量:
const current = window.location.href;
document.querySelectorAll(`#nav-tab a[href*="${current}"]`).forEach(elem => {
elem.classList.add("active");
});
这使用属性选择器a[href*=...]
来选择具有href
包含存储在current
中的文本的a
元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.