jQuery:查找与当前 URL 最匹配的链接

发布于 2024-12-08 07:42:14 字数 1248 浏览 0 评论 0原文

我有以下代码,尝试将选定的类添加到与网址匹配的链接中:

var pathname = window.location.pathname;

$(document).ready(function ()
{
    $('ul#ui-ajax-tabs li a').each(function()
    {
        if (pathname.indexOf($(this).attr('href')) == 0)
        {
            $(this).parents('li').addClass('selected');
        }
    });
});

1.)例如,如果我有一个像 /Organizations/Journal/Organizations 这样的网址/Journal/Edit 与组织和期刊的链接将显示为已选中。这很好!

2.) 但是有时我的网址如下:/Organizations/Organizations/Archived,如果我有指向已存档的链接,则两者都会被选中BUT< /strong> 我不希望发生这种情况,因为类似的组织没有网址的第二部分,因此不应该匹配。

任何人都可以帮助使其适用于第二种类型而不破坏第一种类型吗?此外,这些都不能是硬编码的正则表达式来查找关键字,因为网址有很多不同的参数!

干杯

示例:

如果网址是 /Organizations//Organizations,则应选择带有 /Organizations 的链接。如果 URL 为 /Organizations/Journal/New,则将选择包含 /Organizations/Journal/Organizations/Journal/New 的链接。

但是,如果我有一个带有 /Organizations/Recent 的网址,并且有两个链接:/Organizations/Organizations/Recent 那么只有第二个应该是已选中!因此,这里需要注意的是,它必须有第三个参数,然后才能更松散地而不是精确匹配地查找 URL 的位。

请记住,它可能并不总是组织,因此不能将其硬编码到 JS 中!

I have the following code which tries to add a class of selected to a link that matches the url:

var pathname = window.location.pathname;

$(document).ready(function ()
{
    $('ul#ui-ajax-tabs li a').each(function()
    {
        if (pathname.indexOf($(this).attr('href')) == 0)
        {
            $(this).parents('li').addClass('selected');
        }
    });
});

1.) So for example if I have a url like /Organisations/Journal and /Organisations/Journal/Edit a link with Organisations and Journal will show as being selected. This is fine!

2.) However sometimes I have urls like: /Organisations and /Organisations/Archived and if I have a link to the Archived then both will be selected BUT I don't want this to happen because the Organisations like doesn't have the second part of the url so shouldn't match.

Can anyone help with getting this working for the second types Without breaking the first type? Also none of this can be hardcoded regex looking for keywords as the urls have lots of different parameters!

Cheers

EXAMPLES:

If the url is /Organisations/ Or /Organisations then a link with /Organisations should be selected. If the URL is /Organisations/Journal/New then a link with /Organisations/Journal or /Organisations/Journal/New would be selected.

BUT if I have a url with /Organisations/Recent and have two links: /Organisations and /Organisations/Recent then only the second should be selected! So the thing to note here is that it must have a third parameter before it should look for bits of the URL more loosly rather than an exact match.

Remember it might not always be Organisations so it can't be hardcoded into the JS!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

撕心裂肺的伤痛 2024-12-15 07:42:14

编辑:我以前的解决方案非常复杂。更新了答案和fiddle

var pathname = window.location.pathname;

$(document).ready(function ()
{
    var best_distance = 999; // var to hold best distance so far
    var best_match = false;  // var to hold best match object

    $('ul#ui-ajax-tabs li a').each(function()
    {
        if (pathname.indexOf($(this).attr('href')) == 0)
        {
            // we know that the link is part of our path name.
            // the next line calculates how many characters the path name is longer than our link
            overlap_penalty = pathname.replace($(this).attr('href'), '').length;
            if (overlap_penalty < best_distance) { // if we found a link that has less difference in length that all previous ones ...
                best_distance = overlap_penalty; // remember the length difference
                best_match = this; // remember the link
            }
        }
    });

    if (best_match !== false)
    {
        $(best_match).closest('li').addClass('selected');
    }
});

最佳匹配的计算方式如下:

假设我们的路径名是“/foo/bar/baz/x”。
我们有两个有问题的链接:

  • /foo/bar/
  • /foo/bar/baz

这就是发生的情况:

  1. /foo/bar/baz/x (第一个链接的 url 从路径名 < 中删除) code>pathname.replace($(this).attr('href'), ''))
  2. 剩下的就是“baz/x”。
  3. 剩余部分的字符数(长度)为 5。这是我们对该链接的“惩罚”。
  4. 我们将 5 与之前的最佳距离进行比较 (if (overlap_penalty < best_distance))。 5 低于(=更好)于 999。
  5. 我们保存 this (即 DOM 对象)以供稍后使用使用。
  6. 第二个链接以相同的方式处理:
  7. /foo/bar/baz/x(第二个链接的 url 从路径名中删除)
  8. “/x”是剩下的。
  9. 该余数的字符数为 2。
  10. 我们将 2 与之前的最佳距离(即 5)进行比较。 2 小于 5。
  11. 我们保存 this (即 DOM 对象)以供以后使用。

最后,我们只是检查是否找到任何匹配的链接,如果是,则将 addClass('selected') 应用于其最接近的

  • 父级。
  • Edit: My previous solution was quite over-complicated. Updated answer and fiddle.

    var pathname = window.location.pathname;
    
    $(document).ready(function ()
    {
        var best_distance = 999; // var to hold best distance so far
        var best_match = false;  // var to hold best match object
    
        $('ul#ui-ajax-tabs li a').each(function()
        {
            if (pathname.indexOf($(this).attr('href')) == 0)
            {
                // we know that the link is part of our path name.
                // the next line calculates how many characters the path name is longer than our link
                overlap_penalty = pathname.replace($(this).attr('href'), '').length;
                if (overlap_penalty < best_distance) { // if we found a link that has less difference in length that all previous ones ...
                    best_distance = overlap_penalty; // remember the length difference
                    best_match = this; // remember the link
                }
            }
        });
    
        if (best_match !== false)
        {
            $(best_match).closest('li').addClass('selected');
        }
    });
    

    The best match is calculated like so:

    Assume our pathname is "/foo/bar/baz/x".
    We have two links in question:

    • /foo/bar/
    • /foo/bar/baz

    This is what happens:

    1. /foo/bar/baz/x (the first link's url is deleted from the path name pathname.replace($(this).attr('href'), ''))
    2. "baz/x" is what remains.
    3. The character count (length) of this remainder is 5. this is our "penalty" for the link.
    4. We compare 5 to our previous best distance (if (overlap_penalty < best_distance)). 5 is lower (=better) than 999.
    5. We save this (being the <a href="/foo/bar/"> DOM object) for possible later use.
    6. The second link is handled in the same manner:
    7. /foo/bar/baz/x (the second link's url is deleted from the path name)
    8. "/x" is what remains.
    9. The character count of this remainder is 2.
    10. We compare 2 to our previous best distance (being 5). 2 is lower than 5.
    11. We save this (being the <a href="/foo/bar/baz"> DOM object) for possible later use.

    In the end, we just check if we found any matching link and, if so, apply addClass('selected') to its closest <li> parent.

    对岸观火 2024-12-15 07:42:14

    你为什么不使用

    if($(this).attr('href') == pathname )
    

    而不是

    if (pathname.indexOf($(this).attr('href')) == 0)
    

    Why dont u use

    if($(this).attr('href') == pathname )
    

    instead of

    if (pathname.indexOf($(this).attr('href')) == 0)
    
    旧竹 2024-12-15 07:42:14
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title></title>
        <script src="Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            $(document).ready(function () {
                var windowLocationPathname = "/HTMLPage14.htm";  // For testing purpose.
    
                //Or
    
                //var windowLocationPathname = window.location.pathname;
    
                $('ul.ui-ajax-tab').find('a[href^="' + windowLocationPathname + '"]').addClass('currentPage');
            });
        </script>
        <style type="text/css">
            .ui-ajax-tab
            {
                list-style: none;
            }
    
            a.currentPage
            {
                color: Red;
                background-color: Yellow;
            }
        </style>
    </head>
    <body>
        <ul class="ui-ajax-tab">
            <li><a href="/HTMLPage14.htm">Test 1 (/HTMLPage14.htm)</a></li>
            <li><a href="/HTMLPage15.htm">Test 2 (/HTMLPage15.htm)</a></li>
            <li><a href="/HTMLPage16.htm">Test 3 (/HTMLPage16.htm)</a></li>
            <li><a href="/HTMLPage17.htm">Test 4 (/HTMLPage17.htm)</a></li>        
        </ul>
    </body>
    </html>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title></title>
        <script src="Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            $(document).ready(function () {
                var windowLocationPathname = "/HTMLPage14.htm";  // For testing purpose.
    
                //Or
    
                //var windowLocationPathname = window.location.pathname;
    
                $('ul.ui-ajax-tab').find('a[href^="' + windowLocationPathname + '"]').addClass('currentPage');
            });
        </script>
        <style type="text/css">
            .ui-ajax-tab
            {
                list-style: none;
            }
    
            a.currentPage
            {
                color: Red;
                background-color: Yellow;
            }
        </style>
    </head>
    <body>
        <ul class="ui-ajax-tab">
            <li><a href="/HTMLPage14.htm">Test 1 (/HTMLPage14.htm)</a></li>
            <li><a href="/HTMLPage15.htm">Test 2 (/HTMLPage15.htm)</a></li>
            <li><a href="/HTMLPage16.htm">Test 3 (/HTMLPage16.htm)</a></li>
            <li><a href="/HTMLPage17.htm">Test 4 (/HTMLPage17.htm)</a></li>        
        </ul>
    </body>
    </html>
    
    ~没有更多了~
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文