0

我使用 ajax 在 div 容器中加载 html 页面。html 内容在元素单击时加载,如下所示:

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

如果 Internet 浏览器中的 url 哈希与$(".link").attr("href"). 所以当我再次点击同一个元素时,我希望什么都不会发生。

目前,如果我再次单击同一个元素,则会通过 ajax 调用加载相同的内容。

洛伊克

4

3 回答 3

0

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

于 2013-03-23T15:42:34.383 回答
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;
});
于 2013-03-23T16:01:56.523 回答
0

将选择器从 更改$(".link")$(".link:not(.current)"),因此您的点击处理程序只会在没有类的链接上被调用current

更新:这不起作用,因为 jQuery 将 click 函数分配给 document.ready 上的所有链接(或将执行此代码的任何位置)并且不检查点击时的选择器。因此,您需要检查current单击处理程序中的类,如下所示:

$(".link").click(function () {
  if($(this).hasClass('current')) return false;
  ...
});
于 2013-03-23T15:39:50.657 回答