我必须让链接处于事件状态,并使用获取 url
的第二部分的代码,并使用 搜索
等于 nav li a
元素>hrefurl
的第二部分。
当我访问我的网站时,第一个像 U 的网站是 www.domain.com
,没有任何 /index.php
或 /contact-us。 php
.这是一个问题,因为我的 url 的第二部分将为空并告诉我的所有 a
元素处于事件状态。
当我按下标题链接 1 时,一切正常。 这是the site我说的是,如果你愿意的话,你自己看看吧☺。
代码:
$(function () {
var current = location.pathname;
//Here
$('nav li a').each(function () {
var $this = $(this);
// if the current path is like this link, make it active
if ($this.attr('href').indexOf(current) !== -1) {
$this.addClass('selected');
}
})
});
我从 this stackoverflow question 找到了这段代码.
我尝试在上面代码的 //Here
位置添加下面的代码:
if ($this.attr('href') === window.location.href){
$this.attr('href', window.location.href + "/index.php"');
}
但正如你所看到的,我还不是编码专家(还☺),所以我无法让它工作。有人可以帮助我解决这个问题或引导我走向正确的方向吗?
最佳答案
您已经非常接近实现您想要的目标,但您错过了一个测试:
location.pathname将仅返回主 URL 之后的路径,这意味着当我们的 URL 为 www.domain.com/pageX.php
时,location.pathname
的结果将是 /pageX.php
.
因此,当我们在主页上时,我们的 URL 就是 www.domain.com/
,路径名就是 /
。
$(function () {
var current = location.pathname;
//Here
$('nav li a').each(function () {
var $this = $(this);
// if the current path is like this link, make it active
if(current != "/"){ //<== Means we are not in the homepage, current is /pageX...
if ($this.attr('href').indexOf(current) !== -1) {
$this.addClass('selected');
}
}else{
if ($this.attr('href').indexOf('index.php') !== -1) {
$this.addClass('selected');
}
}
})
});
关于javascript - 不带 www.domain.com/subpage 的 URL 会使每个标题链接开始事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48519087/