javascript - 不带 www.domain.com/subpage 的 URL 会使每个标题链接开始事件

标签 javascript jquery

我必须让链接处于事件状态,并使用获取 url 的第二部分的代码,并使用 搜索 nav li a 元素>href 等于 url 的第二部分。

当我访问我的网站时,第一个像 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/

相关文章:

javascript - 了解 node.js 中的异步函数

javascript - 创建比特币原始交易需要所有余额

javascript - 如何将日期转换为 GMT?

jquery - jqgrid 中带有 JSON 数据的树形网格

javascript - 如何在一页wordpress中禁用所有脚本和样式表

javascript - 像老板一样根据数据在 D3 中设置颜色

javascript - 在 Javascript 中对具有可变深度的多维对象数组进行排序

javascript - Jquery 无冲突 jquery-1.7.1.min.js

javascript - 我的 jquery 在我的待办事项列表中不起作用

jquery - 能否使用 jQuery 的 $(responseXML) 语法可靠地解析 XML?