0

好的,我让这个脚本工作了 99% 的工作方式,但我似乎无法弄清楚这一点。

当用户单击链接时,它会获取 href 值并将其切碎并给我 url 的最后一段。在这个例子中,我会说它的家

所以我的脚本然后抓取回家并将其添加到地址栏中的 url。所以它看起来就像http://www.site.com/user/s2xi/home在它完成了它的魔法之后。

但最初我遇到了一个问题,由于链接工作方式的性质,我想它会继续像这样附加我的 url,http://www.site.com/user/s2xi#/home这在我的服务器上不存在

所以我能够摆脱 # 并且它让一切恢复正常......哦等等,并非一切都在第一次尝试时总是完美......

所以我意识到我的脚本是在附加链接名称而不是替换它们......哦,不,现在怎么办?

我的链接现在看起来像这样:http://www.site.com/user/s2xi/home/someOtherLink

它会将新链接名称附加到旧链接名称而不是替换它...

我的脚本:

var newHash    = "",
        shref      = "",
        content    = '#content',
        $c         = $("#content"),
        $cw        = $("#content-wrapper");

    $(".menu-link, #my-account-link").live('click', function(){
        shref = $(this).attr("href").split("/");
        parent.location.hash = $(this).attr("href");
        window.location.hash = shref[5];
        console.log(window.location.hash);
        return false;
    });

    $(window).bind('hashchange', function(){
        if (location.href.indexOf("#") > -1) {
            location.assign(location.href.replace(/\/?#/, "/"));
        }
        newHash = window.location.hash;
        //newHash = window.location.hash.substring(1);
        //newHash = window.location.substring(1);
        //console.log(newHash);
        if(newHash)
        {
            $cw.find(content).fadeOut(200, function() {
                $cw.load(newHash + " #content-wrapper", function() {
                    $c.fadeIn();
                });
            });
        }
    });
    $(window).trigger('hashchange');

脚本逻辑有什么问题?

4

1 回答 1

0

首先,没有/.../g,您只是替换了第一个匹配项,这可能是您想要的。

你的逻辑似乎是:

  1. 将 # 替换为链接,因此哈希现在变成了链接
  2. 当您单击一个链接时,处理程序会获取当前 href 属性中的最后一段并将其放入哈希中。 请注意,您尚未从 url 中删除该段

换句话说,假设它以:

http://www.site.com/user/s2xi

例如,您的 href 是http://www.site.com/user/s2xi/home。然后在你点击时,你会得到 shref[5] = "home"。然后将其添加到当前 url 的哈希中,这使得它:

http://www.site.com/user/s2xi#home

然后将该哈希转换回链接:

http://www.site.com/user/s2xi/home

一切皆好。第二次单击链接时,例如http://www.site.com/user/s2xi/foo。点击后,shref[5] = "foo"。

然后将其添加到当前 url 的哈希中:

http://www.site.com/user/s2xi/home#foo

然后将该哈希转换回链接:

http://www.site.com/user/s2xi/home/foo

瞧。您附加了链接而不是替换它。您应该替换 url 中的段。

于 2011-03-18T10:34:30.147 回答