避免重新加载ajax内容

I use ajax to load html page inside a div container. The html content is loaded on element click like this :

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

I want to avoid to reload the content if the url hash in the internet browser is the same as the $(".link").attr("href"). So when I click the same element again, I want that nothing happen.

Currently, if I click again on the same element, the same content is loaded with the ajax call.

Loïc

Change the selector from $(".link") to $(".link:not(.current)"), so your click handler will only be called on links that are don't have the class current.

Update: That doesn't work, because jQuery assigns the click function to all links on document.ready (or wherever this code will be executed) and doesn't check the selector on click. So you need to check for the class current in the click handler, like so:

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

You could simply use the window.location object (or simply location if window is the current scope) and compare it to the href property of your link.

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

If your link is a relative path, you could use location.pathname instead of location.href

You could use the fact that you add the "current" class to the selected link to conditionally execute the code in the handler, like this:

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