Javascript 使用jQuery和Ajax处理锚点(散列)链接
假设我要导航到以下链接:Javascript 使用jQuery和Ajax处理锚点(散列)链接,javascript,jquery,ajax,hyperlink,Javascript,Jquery,Ajax,Hyperlink,假设我要导航到以下链接: http://www.mysite.com/feature#linktosection http://www.mysite.com/feature是用jQuery ajax加载的,因此在加载ajax内容之前,我无法导航到#linktosection。加载后,我需要导航(可能模拟单击)到#linktosection 这是我的jQuery ajax调用: $('.changecontext-button').click(function() { $.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
高级版谢谢。内容加载后:
$('a[name=' + window.location.hash + ']').get(0).scrollIntoView();
最后,我实现了它,如下所示:
$('.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);
}
});
});
这就是在加载内容后调用时对我有效的方法:
window.location.hash = window.location.hash
将该代码放入
success:
函数中。它接受window.location.hash
(URL中散列部分后的位),然后找到作为name
属性的锚点,并将该元素滚动到视图中。这不起作用。window.location.hash返回空,因为我的当前URL没有锚。锚点位于$(this.attr('href')
属性上,因此此解决方案对我无效。啊,我明白了。那么为什么不直接做window.location.hash=$('a',data.attr('name')代码>在您的成功函数中?
window.location.hash = window.location.hash