程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长


+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

链接是否指向此页面?

发布于2021-10-10 00:25     阅读(1187)     评论(0)     点赞(26)     收藏(5)


对于我的网站导航,我想为当前页面的所有链接设置颜色。
如何找到指向当前页面的链接?
链接href就像“../index.php”,但当前页面是http://mysite.myserver.com/index.php

这是我目前的方法,它不想工作:

String.prototype.endsWith = function(str) { return ( this.match(str + "$") == str ); }
String.prototype.startsWith = function(str) { return ( this.match("^" + str) == str ) }
String.prototype.trim = function(sec)
{
    var res = this;

    while (res.startWith(sec))
    {
        res = res.substr(sec.length);
    }

    while (res.endsWith(sec))
    {
        res = res.substr(0, res.length - sec.length);
    }

    return res;
}

并且,当文件准备好时:

$("a").each(
    function (i)
    {
        if (window.location.pathname.endsWith($(this).attr("href").trim(".")))
        {
            $(this).addClass("thispage");
        }
    }
);

是的,我知道这可能会给主页链接着色(../index.php - 因为所有页面都以此结尾!)。这就是为什么我需要一个更好的方法......


解决方案


$("a[href]").filter(function() {
    return window.location.pathname === this.pathname;
}).addClass("thispage");

关于您的评论,如果 window.location 是一个目录,您可以创建一个以index.php.

var win = window.location.pathname; 
if( win.slice(-1) === '/' ) { 
    win += 'index.php'; 
} 
$("a[href]").filter(function() {
    return win === this.pathname;
}).addClass("thispage");



所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接:http://www.qianduanheidong.com/blog/article/200010/80214a62c828119a195b/

来源:前端黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

26 0
收藏该文
已收藏

评论内容:(最多支持255个字符)