【问题标题】:Make active links with jQuery?使用 jQuery 创建活动链接?
【发布时间】:2014-07-28 07:45:53
【问题描述】:

我正在像这样与 jQuery 建立活动链接

$(document).ready(function() {
    var url = window.location.href;

    $(".main-navigation ul li a").each(function() {
      var $this = $(this);

        var href = $this.attr("href");

        if (url === href) {

            $this.css({
                'color': '#666666',
                'font-weight': 'bold',
            }).addClass('active').removeAttr("href").removeAttr("onclick");         
        }           
    });

唯一的问题是我的 a href 是这样的 /Settings/File?id=333

网址会是这样的

http://www.example.com/Settings/File?id=333

那么a href和ulr不匹配,如何删除url的http和example并用a href检查?

【问题讨论】:

标签: jquery arrays indexof


【解决方案1】:

首先:如果你要给他们一个类,不要在那里放置额外的内联 CSS...

这里有一个应该可以工作的狙击手......

var uri = window.location.href;
$(".main-navigation ul li a").filter(function() {
    return (this.href == uri || uri.substr(0,this.href.length + 1) == this.href + "?");
}).css({
    'color': '#666666',
    'font-weight': 'bold',
}).addClass('active').removeAttr("href").removeAttr("onclick");

【讨论】:

    【解决方案2】:

    您要将http://www.example.com/Setting/File?id=333 更改为/Setting/File?id=333

    var url = window.location.href.split('.com').pop();
    

    如果你不知道它是否是一个 .com 网站,试试这个:

    function getLocation(url) {
        var el = document.createElement("a");
        el.href = url;
        return el.pathname;
    }
    
    var url = getLocation(window.location.href);
    

    【讨论】:

    • 好的,但问题是 .com??我不知道它会是 .com 吗?
    【解决方案3】:

    要获得/Settings/File?id=333,请使用:

    $this[0].pathname;
    

    Get pathname from href in Javascript

    Location pathname Property

    【讨论】:

    • 没关系,当我有 .com 时,问题是我不知道它会是 .com
    • window.location.pathname 只为您提供路径:-)
    • @DoXicK 和 $this.attr("href"); ?
    • 在http(s)://的第一个/之后拆分它://
    • @Schneider 看到我的编辑使用Location pathname Property
    【解决方案4】:

    你可以使用原生的 a 元素 DOM 和它的 href 它会给出完整的 url:

    $(function(){
      var url = window.location.href;
    
      $(".main-navigation ul li a").each(function() {
        if (url === this.href) {
          $(this).css({
            'color': '#666666',
            'font-weight': 'bold',
          }).addClass('active').removeAttr("href").removeAttr("onclick");
        }
      });
    });
    

    example on jsbin(列表中的第一项具有相同的url,没有域)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-19
      • 2011-10-16
      • 1970-01-01
      • 1970-01-01
      • 2011-05-25
      • 1970-01-01
      • 1970-01-01
      • 2015-04-03
      相关资源
      最近更新 更多