使用jQuery和Ajax处理锚点(哈希)链接
假设我想导航到以下链接:
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链接并将其分成基本URL和锚定URL 。 成功后,我可以使用jQuery选择器来获取锚链接并模拟.click()。
有没有其他更好的选择,使用jQuery或JavaScript?
提前致谢。
最后,我实现如下:
$('.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); }
加载内容后:
$('a[name=' + window.location.hash + ']').get(0).scrollIntoView();
在加载内容后调用时,这对我有用:
window.location.hash = window.location.hash