【问题标题】:Process anchor (hash) links with jQuery and Ajax使用 jQuery 和 Ajax 处理锚(散列)链接
【发布时间】:2011-05-23 13:11:10
【问题描述】:

假设我想导航到以下链接:

http://www.mysite.com/feature#linktosection

http://www.mysite.com/feature 的内容是用 jQuery ajax 加载的,所以在加载 ajax 内容之前我无法导航到#linktosection。加载后,我需要导航(可能模拟点击)到#linktosection

这是我的 jQuery ajax 调用:

$('.changecontext-button').click(function()
{
    $.ajax({                                                           
        type: "POST",                                                  
        url: $(this).attr('href'),
        success: function(data) {
            diffSection.html(data);
        },
        error: function(xhr, textStatus, errorThrown) {
            diffSection.html(xhr.responseText);
        }
    });
});

你知道如何用 jQuery 做到这一点吗?

另一种方法是解析 href 链接并将其分成 base urlanchor url。如果成功,我可以使用 jQuery 选择器来获取锚链接并模拟 .click()。

还有其他更好的选择吗,使用 jQuery 或 JavaScript?

提前致谢。

【问题讨论】:

    标签: javascript jquery ajax hyperlink


    【解决方案1】:

    内容加载后:

    $('a[name=' + window.location.hash + ']').get(0).scrollIntoView();
    

    【讨论】:

    • 将该代码放入您的success: 函数中。它采用window.location.hash(URL 中哈希部分之后的位),然后找到带有name 属性的锚点,并将该元素滚动到视图中。
    • 这不起作用。 window.location.hash 返回空,因为我当前的 URL 没有锚。锚点位于 $(this).attr('href') 属性上,因此此解决方案对我无效。
    • 啊,我明白了。那么为什么不在你的成功函数中做window.location.hash = $('a',data).attr('name');呢?
    【解决方案2】:

    最后我实现如下:

    $('.changecontext-button').click(function()
    {
        var targetUrl = $(this).attr('href');
        $.ajax({                                                           
            type: "POST",                                                  
            url: targetUrl,
            success: function(data) {
                diffSection.html(data);
                var anchor = getAnchor(targetUrl);
                if (anchor)
                {
                    $(anchor).click();
                }
            },
            error: function(xhr, textStatus, errorThrown) {
                    diffSection.html(xhr.responseText);
            }
        });
    });
    

    ...

    function getAnchor(url)
    {
        var index = url.lastIndexOf('#');
        if (index != -1)
            return url.substring(index);
    }
    

    【讨论】:

      【解决方案3】:

      这对我有用,在加载内容后调用:

      window.location.hash = window.location.hash
      

      【讨论】:

        猜你喜欢
        • 2013-01-20
        • 1970-01-01
        • 2017-09-02
        • 1970-01-01
        • 1970-01-01
        • 2013-02-02
        • 1970-01-01
        相关资源
        最近更新 更多