2013-03-23 69 views
0

我用Ajax加载一个div容器内的HTML页面。 HTML内容加载元素上点击这样的:避免重装Ajax内容

$(".link").click(function() { 
    $('.link').removeClass('current'); 
    $(this).addClass('current'); 
    ajaxify($(this).attr('href')); 
    window.location.hash = $(this).attr("href"); 
    return false; 
}); 

我想避免重新加载的内容,如果在互联网浏览器的URL哈希值是一样的$(".link").attr("href")。 所以当我再次点击相同的元素时,我希望没有任何事情发生。

目前,如果我在相同的元素再次点击,相同的内容加载Ajax调用。

卢瓦克

+0

'ajaxify()'做了什么?这是图书馆的功能,还是你写的东西。 – 2013-03-23 16:03:40

回答

0

更改选择从$(".link")$(".link:not(.current)"),让你的点击处理将只对那些不具备类current链接调用。

更新:这是不行的,因为jQuery分配点击功能上的document.ready(或其它地方的代码会被执行)和点击不检查选择的所有链接。因此,你需要在点击处理程序来检查类current,像这样:

$(".link").click(function() { 
    if($(this).hasClass('current')) return false; 
    ... 
}); 
+0

谢谢你,但它不会改变任何东西.. – lolo 2013-03-23 15:57:47

+0

我更新我的回答 – darthmaim 2013-03-23 16:03:18

0

你可以简单地使用window.location对象(或简称location如果window是当前范围),并比较它的href财产你的链接。

$(".link").click(function() { 
    if ($(this).attr('href') != location.href) { 
     $('.link').removeClass('current'); 
     $(this).addClass('current'); 
     ajaxify($(this).attr('href')); 
     window.location.hash = $(this).attr("href"); 
     return false; 
    } 
}); 

如果你的链接是一个相对路径,可以使用的location.pathname代替location.href

+0

谢谢。我试过这段代码,但它不起作用。内容仍然重新加载。我只是确切的说,href没有散列,浏览器url在我的ajax内容加载器中添加了一个散列。 – lolo 2013-03-23 15:57:25

+0

请放的console.log($(本).attr( 'href' 属性))例如 – martriay 2013-03-23 23:58:47

+0

谢谢,但问题是这种解决:( '链接')$点击(函数(){VAR 链接= $。 ('。'); if(!link.hasClass('current') ( 'HREF')); window.location.hash = link.attr(的 “href”);} 返回false; }); – lolo 2013-03-24 00:04:45

0

你可以使用这个事实,你添加“当前”类选择链接到在有条件地执行代码处理程序,如下所示:

$('.link').click(function() { 
    var link = $(this); 
    if (!link.hasClass('current')) { 
     $('.link').removeClass('current'); 
     link.addClass('current'); 
     ajaxify(link.attr('href')); 
     window.location.hash = link.attr("href"); 
    } 
    return false; 
}); 
+0

非常感谢!它的作品非常了解! – lolo 2013-03-23 16:08:33