Process anchor (hash) links with jQuery and Ajax

故事扮演 提交于 2019-12-24 05:01:27

问题


Suppose I want to navigate to the following link:

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

The content of http://www.mysite.com/feature is loaded with jQuery ajax, so I cannot navigate to #linktosection until the ajax content has been loaded. Once it is loaded I need to navigate (maybe simulate a click) to #linktosection

This is my jQuery ajax call:

$('.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);
        }
    });
});

Do you know how to do this with jQuery?

An alternative could be parsing the href link and separate it into a base url and an anchor url. The, on success I could use a jQuery selector to get the anchor link and simulate a .click().

Is there any other better alternative, using jQuery or JavaScript?

Thanks in advanced.


回答1:


Finally, I implemented it as follows:

$('.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);
}



回答2:


After your content has loaded:

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



回答3:


This is, what works for me, when called after content is loaded:

window.location.hash = window.location.hash


来源:https://stackoverflow.com/questions/4410169/process-anchor-hash-links-with-jquery-and-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!